﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Xml;

#if (!WindowsCE && !PocketPC)
using System.Reflection.Emit;
#endif


namespace InkFx.WinControl.Utils
{
    /// <summary>
    /// 通过反射, 对 对象进行 动态赋值、取值、数据类型转换 等。
    /// [[本静态类 有两个 默认AppSetting参数: ReflectHelper_GetValueType='Emit|Reflect' ReflectHelper_SetValueType='Emit|Reflect' 默认都是 Reflect ]]
    /// 感谢作者 舒小龙(http://www.ink-fx.com) 为下面 1000 行 高性能代码, 作出的贡献.
    /// </summary>
    internal static class ReflectHelper
    {
        #region  特 性 判 断

        /// <summary>
        /// 获取指定 特性T
        /// </summary>
        public static T GetAttribute<T>(MemberInfo member) where T : Attribute
        {
            List<T> list = GetAttributes<T>(member);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性T 的集合
        /// </summary>
        public static List<T> GetAttributes<T>(MemberInfo member) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(member, true);
            if (attrs.Length <= 0) return null;

            List<T> list = new List<T>();
            foreach (Attribute attr in attrs)
                if (attr is T) list.Add((T)attr);

            return list;
        }
        /// <summary>
        /// 获取指定 特性 attrName
        /// </summary>
        public static Attribute GetAttribute(MemberInfo member, string attrName)
        {
            List<Attribute> list = GetAttributes(member, attrName);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性 attrName 的集合
        /// </summary>
        public static List<Attribute> GetAttributes(MemberInfo member, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(member, true);
            if (attrs.Length <= 0) return null;

            List<Attribute> list = new List<Attribute>();
            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) list.Add(attr);

            return list;
        }
        /// <summary>
        /// 判断是否存在 特性T
        /// </summary>
        public static bool HasAttribute<T>(MemberInfo member) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(member, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (attr is T) return true;

            return false;
        }
        /// <summary>
        /// 判断是否存在 特性attrName
        /// </summary>
        public static bool HasAttribute(MemberInfo member, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(member, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) return true;

            return false;
        }




        /// <summary>
        /// 获取指定 特性T
        /// </summary>
        public static T GetAttribute<T>(Module module) where T : Attribute
        {
            List<T> list = GetAttributes<T>(module);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性T 的集合
        /// </summary>
        public static List<T> GetAttributes<T>(Module module) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(module, true);
            if (attrs.Length <= 0) return null;

            List<T> list = new List<T>();
            foreach (Attribute attr in attrs)
                if (attr is T) list.Add((T)attr);

            return list;
        }
        /// <summary>
        /// 获取指定 特性 attrName
        /// </summary>
        public static Attribute GetAttribute(Module module, string attrName)
        {
            List<Attribute> list = GetAttributes(module, attrName);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性 attrName 的集合
        /// </summary>
        public static List<Attribute> GetAttributes(Module module, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(module, true);
            if (attrs.Length <= 0) return null;

            List<Attribute> list = new List<Attribute>();
            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) list.Add(attr);

            return list;
        }
        /// <summary>
        /// 判断是否存在 特性T
        /// </summary>
        public static bool HasAttribute<T>(Module module) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(module, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (attr is T) return true;

            return false;
        }
        /// <summary>
        /// 判断是否存在 特性attrName
        /// </summary>
        public static bool HasAttribute(Module module, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(module, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) return true;

            return false;
        }




        /// <summary>
        /// 获取指定 特性T
        /// </summary>
        public static T GetAttribute<T>(ParameterInfo param) where T : Attribute
        {
            List<T> list = GetAttributes<T>(param);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性T 的集合
        /// </summary>
        public static List<T> GetAttributes<T>(ParameterInfo param) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(param, true);
            if (attrs.Length <= 0) return null;

            List<T> list = new List<T>();
            foreach (Attribute attr in attrs)
                if (attr is T) list.Add((T)attr);

            return list;
        }
        /// <summary>
        /// 获取指定 特性 attrName
        /// </summary>
        public static Attribute GetAttribute(ParameterInfo param, string attrName)
        {
            List<Attribute> list = GetAttributes(param, attrName);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性 attrName 的集合
        /// </summary>
        public static List<Attribute> GetAttributes(ParameterInfo param, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(param, true);
            if (attrs.Length <= 0) return null;

            List<Attribute> list = new List<Attribute>();
            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) list.Add(attr);

            return list;
        }
        /// <summary>
        /// 判断是否存在 特性T
        /// </summary>
        public static bool HasAttribute<T>(ParameterInfo param) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(param, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (attr is T) return true;

            return false;
        }
        /// <summary>
        /// 判断是否存在 特性attrName
        /// </summary>
        public static bool HasAttribute(ParameterInfo param, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(param, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) return true;

            return false;
        }




        /// <summary>
        /// 获取指定 特性T
        /// </summary>
        public static T GetAttribute<T>(Assembly assembly) where T : Attribute
        {
            List<T> list = GetAttributes<T>(assembly);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性T 的集合
        /// </summary>
        public static List<T> GetAttributes<T>(Assembly assembly) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(assembly, true);
            if (attrs.Length <= 0) return null;

            List<T> list = new List<T>();
            foreach (Attribute attr in attrs)
                if (attr is T) list.Add((T)attr);

            return list;
        }
        /// <summary>
        /// 获取指定 特性 attrName
        /// </summary>
        public static Attribute GetAttribute(Assembly assembly, string attrName)
        {
            List<Attribute> list = GetAttributes(assembly, attrName);
            return (list != null && list.Count >= 1) ? list[0] : null;
        }
        /// <summary>
        /// 获取指定 特性 attrName 的集合
        /// </summary>
        public static List<Attribute> GetAttributes(Assembly assembly, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(assembly, true);
            if (attrs.Length <= 0) return null;

            List<Attribute> list = new List<Attribute>();
            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) list.Add(attr);

            return list;
        }
        /// <summary>
        /// 判断是否存在 特性T
        /// </summary>
        public static bool HasAttribute<T>(Assembly assembly) where T : Attribute
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(assembly, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (attr is T) return true;

            return false;
        }
        /// <summary>
        /// 判断是否存在 特性attrName
        /// </summary>
        public static bool HasAttribute(Assembly assembly, string attrName)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(assembly, true);
            if (attrs.Length <= 0) return false;

            foreach (Attribute attr in attrs)
                if (string.Equals(attr.GetType().Name, attrName, StringComparison.InvariantCultureIgnoreCase)) return true;

            return false;
        }










        #endregion



        #region  程 序 集 注 释

        /// <summary>
        /// 获取 指定类型 的 注释信息, 未能找到则返回 类型Name
        /// </summary>
        public static string GetLibSummary(Type @type)
        {
            if (@type == null) return string.Empty;

            string summary = null;
            //bool isNested = @type.IsNested;
            InvokeLibSummaryXml(@type, (xmlDoc/*, xmlNode*/) =>
            {
                string findKey = string.Format("T:{0}", type.FullName);
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("summary");
                summary = nodeS == null ? string.Empty : nodeS.InnerText.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @type.Name;
        }
        /// <summary>
        /// 获取 指定函数 的 注释信息, 未能找到则返回 函数Name
        /// </summary>
        public static string GetLibSummary(MethodInfo @method)
        {
            if (@method == null || @method.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @method.DeclaringType.IsNested;
            bool isGeneric = method.IsGenericMethod;
            bool isDelegate = method.Name == "Invoke" && method.DeclaringType.IsSubclassOf(typeof(MulticastDelegate));
            List<Type> listGgenericArgs = method.IsGenericMethod ? new List<Type>(method.GetGenericArguments()) : new List<Type>();
            List<Type> listGgenericArgs2 = @method.DeclaringType.IsGenericType ? new List<Type>(@method.DeclaringType.GetGenericArguments()) : new List<Type>();

            InvokeLibSummaryXml(@method, (xmlDoc/*, xmlNode*/) =>
            {
                string methodName = (isDelegate ? "T" : "M") + string.Format(":{0}.{1}{2}", @method.DeclaringType.FullName, (isDelegate ? "" : method.Name), (isDelegate ? "" : (listGgenericArgs.Count >= 1 ? "``" + listGgenericArgs.Count : "")));
                methodName = methodName.Trim('.');
                List<string> listParam = new List<string>();
                if (!isDelegate)
                    foreach (var param in method.GetParameters())
                    {
                        int index = listGgenericArgs.IndexOf(param.ParameterType);
                        int index2 = listGgenericArgs2.IndexOf(param.ParameterType);
                        if (index >= 0) listParam.Add("``" + index);
                        else if (index2 >= 0) listParam.Add("`" + index2);
                        else listParam.Add(param.ParameterType.FullName);
                    }

                string findKey = (listParam.Count <= 0 ? methodName : (methodName + "(" + string.Join(",", listParam.ToArray()) + ")"));
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("summary");
                summary = nodeS == null ? string.Empty : nodeS.InnerXml.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @method.Name;
        }
        /// <summary>
        /// 获取 指定构造函数 的 注释信息, 未能找到则返回 函数Name
        /// </summary>
        public static string GetLibSummary(ConstructorInfo @ctor)
        {
            if (@ctor == null || @ctor.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @ctor.DeclaringType.IsNested;
            List<Type> listGgenericArgs = @ctor.IsGenericMethod ? new List<Type>(@ctor.GetGenericArguments()) : new List<Type>();
            List<Type> listGgenericArgs2 = @ctor.DeclaringType.IsGenericType ? new List<Type>(@ctor.DeclaringType.GetGenericArguments()) : new List<Type>();
            InvokeLibSummaryXml(@ctor, (xmlDoc/*, xmlNode*/) =>
            {
                string methodName = string.Format("M:{0}.{1}{2}", @ctor.DeclaringType.FullName, "#ctor", (listGgenericArgs.Count >= 1 ? "``" + listGgenericArgs.Count : "")); //@ctor.Name
                List<string> listParam = new List<string>();
                foreach (var pm in @ctor.GetParameters())
                {
                    int index = listGgenericArgs.IndexOf(pm.ParameterType);
                    int index2 = listGgenericArgs2.IndexOf(pm.ParameterType);
                    if (index >= 0) listParam.Add("``" + index);
                    else if (index2 >= 0) listParam.Add("`" + index2);
                    else listParam.Add(pm.ParameterType.FullName);
                }

                string findKey = (listParam.Count <= 0 ? methodName : (methodName + "(" + string.Join(",", listParam.ToArray()) + ")"));
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("summary");
                summary = nodeS == null ? string.Empty : nodeS.InnerXml.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return "#ctor"; //@ctor.Name;
        }
        /// <summary>
        /// 获取 指定函数 的 返回值注释信息, 未能找到则返回 空字符串
        /// </summary>
        public static string GetLibRtSummary(MethodInfo @method)
        {
            if (@method == null || @method.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @method.DeclaringType.IsNested;
            bool isGeneric = method.IsGenericMethod;
            bool isDelegate = method.Name == "Invoke" && method.DeclaringType.IsSubclassOf(typeof(MulticastDelegate));
            List<Type> listGgenericArgs = new List<Type>(method.GetGenericArguments());
            List<Type> listGgenericArgs2 = @method.DeclaringType.IsGenericType ? new List<Type>(@method.DeclaringType.GetGenericArguments()) : new List<Type>();
            InvokeLibSummaryXml(@method, (xmlDoc/*, xmlNode*/) =>
            {
                string methodName = (isDelegate ? "T" : "M") + string.Format(":{0}.{1}{2}", @method.DeclaringType.FullName, (isDelegate ? "" : method.Name), (isDelegate ? "" : (listGgenericArgs.Count >= 1 ? "``" + listGgenericArgs.Count : "")));
                methodName = methodName.Trim('.');
                List<string> listParam = new List<string>();
                if (!isDelegate)
                    foreach (var param in method.GetParameters())
                    {
                        int index = listGgenericArgs.IndexOf(param.ParameterType);
                        int index2 = listGgenericArgs2.IndexOf(param.ParameterType);
                        if (index >= 0) listParam.Add("``" + index);
                        else if (index2 >= 0) listParam.Add("`" + index2);
                        else listParam.Add(param.ParameterType.FullName);
                    }

                string findKey = (listParam.Count <= 0 ? methodName : (methodName + "(" + string.Join(",", listParam.ToArray()) + ")"));
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("returns");
                summary = nodeS == null ? string.Empty : nodeS.InnerText.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return string.Empty;
        }

        /// <summary>
        /// 获取 指定事件 的 注释信息, 未能找到则返回 事件Name
        /// </summary>
        public static string GetLibSummary(EventInfo @event)
        {
            if (@event == null || @event.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @event.DeclaringType.IsNested;
            InvokeLibSummaryXml(@event, (xmlDoc/*, xmlNode*/) =>
            {
                string findKey = string.Format("F:{0}.{1}", @event.DeclaringType.FullName, @event.Name);
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("summary");
                summary = nodeS == null ? string.Empty : nodeS.InnerText.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @event.Name;
        }
        /// <summary>
        /// 获取 指定字段 的 注释信息, 未能找到则返回 字段Name
        /// </summary>
        public static string GetLibSummary(FieldInfo @field)
        {
            if (@field == null || @field.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @field.DeclaringType.IsNested;
            InvokeLibSummaryXml(@field, (xmlDoc/*, xmlNode*/) =>
            {
                string findKey = string.Format("F:{0}.{1}", @field.DeclaringType.FullName, @field.Name);
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("summary");
                summary = nodeS == null ? string.Empty : nodeS.InnerText.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @field.Name;
        }
        /// <summary>
        /// 获取 指定属性 的 注释信息, 未能找到则返回 属性Name
        /// </summary>
        public static string GetLibSummary(PropertyInfo @prop)
        {
            if (@prop == null || @prop.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @prop.DeclaringType.IsNested;
            InvokeLibSummaryXml(@prop, (xmlDoc/*, xmlNode*/) =>
            {
                string findKey = string.Format("P:{0}.{1}", @prop.DeclaringType.FullName, @prop.Name);
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("summary");
                summary = nodeS == null ? string.Empty : nodeS.InnerText.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @prop.Name;
        }
        /// <summary>
        /// 获取 指定属性 的 返回值注释信息, 未能找到则返回 空字符串
        /// </summary>
        public static string GetLibRtSummary(PropertyInfo @prop)
        {
            if (@prop == null || @prop.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @prop.DeclaringType.IsNested;
            InvokeLibSummaryXml(@prop, (xmlDoc/*, xmlNode*/) =>
            {
                string findKey = string.Format("P:{0}.{1}", @prop.DeclaringType.FullName, @prop.Name);
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode("returns");
                summary = nodeS == null ? string.Empty : nodeS.InnerText.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return string.Empty;
        }
        /// <summary>
        /// 获取 指定参数 的 注释信息, 未能找到则返回 参数Name
        /// </summary>
        public static string GetLibSummary(ParameterInfo @param)
        {
            if (@param == null) return string.Empty;

            string summary = null;
            InvokeLibSummaryXml(@param, (xmlDoc/*, xmlNode*/) =>
            {
                MethodInfo @method = @param.Member as MethodInfo;
                if (@method == null || @method.DeclaringType == null) return;
                //bool isNested = @method.DeclaringType.IsNested;

                bool isDelegate = method.Name == "Invoke" && method.DeclaringType.IsSubclassOf(typeof(MulticastDelegate));
                List<Type> listGgenericArgs = new List<Type>(method.GetGenericArguments());
                List<Type> listGgenericArgs2 = @method.DeclaringType.IsGenericType ? new List<Type>(@method.DeclaringType.GetGenericArguments()) : new List<Type>();
                string methodName = (isDelegate ? "T" : "M") + string.Format(":{0}.{1}{2}", @method.DeclaringType.FullName, (isDelegate ? "" : method.Name), (isDelegate ? "" : (listGgenericArgs.Count >= 1 ? "``" + listGgenericArgs.Count : "")));
                methodName = methodName.Trim('.');
                List<string> listParam = new List<string>();
                if (!isDelegate)
                    foreach (var pm in method.GetParameters())
                    {
                        int index = listGgenericArgs.IndexOf(pm.ParameterType);
                        int index2 = listGgenericArgs2.IndexOf(pm.ParameterType);
                        if (index >= 0) listParam.Add("``" + index);
                        else if (index2 >= 0) listParam.Add("`" + index2);
                        else listParam.Add(pm.ParameterType.FullName);
                    }

                string findKey = (listParam.Count <= 0 ? methodName : (methodName + "(" + string.Join(",", listParam.ToArray()) + ")"));
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode(string.Format("param[@name='{0}']", @param.Name));
                summary = nodeS == null ? string.Empty : nodeS.InnerText.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @param.Name;
        }

        /// <summary>
        /// 获取 指定类型 的 指定泛型 的 注释信息, 未能找到则返回 函数Name
        /// </summary>
        public static string GetLibSummary(Type @type, Type @genericType)
        {
            if (@type == null) return string.Empty;

            string summary = null;
            //bool isNested = @method.DeclaringType.IsNested;
            bool isGeneric = @type.IsGenericType;
            InvokeLibSummaryXml(@type, (xmlDoc/*, xmlNode*/) =>
            {
                string findKey = string.Format("T:{0}", type.FullName);
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode(string.Format("typeparam[@name='{0}']", @genericType.Name));
                summary = nodeS == null ? string.Empty : nodeS.InnerXml.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @type.Name;
        }
        /// <summary>
        /// 获取 指定函数 的 指定泛型 的 注释信息, 未能找到则返回 函数Name
        /// </summary>
        public static string GetLibSummary(MethodInfo @method, Type @genericType)
        {
            if (@method == null || @method.DeclaringType == null) return string.Empty;

            string summary = null;
            //bool isNested = @method.DeclaringType.IsNested;
            bool isGeneric = method.IsGenericMethod;
            bool isDelegate = method.Name == "Invoke" && method.DeclaringType.IsSubclassOf(typeof(MulticastDelegate));
            List<Type> listGgenericArgs = new List<Type>(method.GetGenericArguments());
            List<Type> listGgenericArgs2 = @method.DeclaringType.IsGenericType ? new List<Type>(@method.DeclaringType.GetGenericArguments()) : new List<Type>();
            InvokeLibSummaryXml(@method, (xmlDoc/*, xmlNode*/) =>
            {
                string methodName = (isDelegate ? "T" : "M") + string.Format(":{0}.{1}{2}", @method.DeclaringType.FullName, (isDelegate ? "" : method.Name), (isDelegate ? "" : (listGgenericArgs.Count >= 1 ? "``" + listGgenericArgs.Count : "")));
                methodName = methodName.Trim('.');
                List<string> listParam = new List<string>();
                if (!isDelegate)
                    foreach (var param in method.GetParameters())
                    {
                        int index = listGgenericArgs.IndexOf(param.ParameterType);
                        int index2 = listGgenericArgs2.IndexOf(param.ParameterType);
                        if (index >= 0) listParam.Add("``" + index);
                        else if (index2 >= 0) listParam.Add("`" + index2);
                        else listParam.Add(param.ParameterType.FullName);
                    }

                string findKey = (listParam.Count <= 0 ? methodName : (methodName + "(" + string.Join(",", listParam.ToArray()) + ")"));
                /*if (isNested)*/
                findKey = findKey.Replace("+", ".");
                XmlNode node = xmlDoc.SelectSingleNode(string.Format("/doc/members/member[@name='{0}']", findKey));
                XmlNode nodeS = node == null ? null : node.SelectSingleNode(string.Format("typeparam[@name='{0}']", @genericType.Name));
                summary = nodeS == null ? string.Empty : nodeS.InnerXml.Trim();
            });
            if (summary != null) return FormatSummary(summary);

            return @method.Name;
        }

        /// <summary>
        /// 获取指定对象或类型 所属的程序集 
        /// </summary>
        public static Assembly GetOwnerAssembly(object obj)
        {
            if (obj == null) return null;

            Assembly assem = null;
            if (obj is Assembly) assem = (Assembly)obj;
            else if (obj is Module) assem = ((Module)obj).Assembly;
            else if (obj is Type) assem = ((Type)obj).Assembly;
            else if (obj is ConstructorInfo) { Type type = ((ConstructorInfo)obj).DeclaringType; assem = type == null ? null : type.Assembly; }
            else if (obj is MethodInfo) { Type type = ((MethodInfo)obj).DeclaringType; assem = type == null ? null : type.Assembly; }
            else if (obj is EventInfo) { Type type = ((EventInfo)obj).DeclaringType; assem = type == null ? null : type.Assembly; }
            else if (obj is FieldInfo) { Type type = ((FieldInfo)obj).DeclaringType; assem = type == null ? null : type.Assembly; }
            else if (obj is PropertyInfo) { Type type = ((PropertyInfo)obj).DeclaringType; assem = type == null ? null : type.Assembly; }
            else if (obj is ParameterInfo) { Type type = ((ParameterInfo)obj).Member.DeclaringType; assem = type == null ? null : type.Assembly; }
            else { assem = obj.GetType().Assembly; }

            return assem;
        }





        private static Dictionary<Assembly, LibSummaryXmlInfo> m_HashLibXml = null;
        private static readonly Regex regSummaryFormat = new Regex(@"<see\s+cref\s*=\s*""\w\:[^""]+""\s+/>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static readonly Regex regSummaryFormatRef = new Regex(@"(?<=cref\s*=\s*""\w\:)[^""]+(?=\s*"")", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        private static LibSummaryXmlInfo InitLibXml(object obj)
        {
            if (obj == null) return null;

            try
            {
                Assembly assem = GetOwnerAssembly(obj);
                if (m_HashLibXml != null && m_HashLibXml.ContainsKey(assem))
                {
                    LibSummaryXmlInfo libXml2 = m_HashLibXml[assem];
                    libXml2.LastRead = DateTime.Now;
                    return libXml2;
                }

                string xmlPath = GetLibXmlPath(assem);
                if (Tools.IsNullOrWhiteSpace(xmlPath) || !File.Exists(xmlPath)) return null;


                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                LibSummaryXmlInfo libXml = new LibSummaryXmlInfo(assem, xmlDoc);

                if (m_HashLibXml == null) m_HashLibXml = new Dictionary<Assembly, LibSummaryXmlInfo>();

                if (m_HashLibXml.ContainsKey(assem)) m_HashLibXml[assem] = libXml;
                else m_HashLibXml.Add(assem, libXml);

                return libXml;
            }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (Exception) { return null; }
        }
        private static string GetLibXmlPath(Assembly assem)
        {
            if (assem == null) return string.Empty;

            try
            {
                string assemPath = assem.Location;
                if (!File.Exists(assemPath)) return string.Empty;
                bool isNetFx = assemPath.IndexOf(@"Microsoft.NET\Framework", StringComparison.InvariantCultureIgnoreCase) >= 0;

                FileInfo fileInfo = new FileInfo(assemPath);
                DirectoryInfo dirInfo = fileInfo.Directory;
                if (dirInfo == null || !dirInfo.Exists) return string.Empty;

                string xmlName = Path.GetFileNameWithoutExtension(fileInfo.FullName) + ".xml";
                string xmlPath = dirInfo.FullName.TrimEnd('/', '\\') + "\\" + xmlName;
                if (File.Exists(xmlPath)) return xmlPath;
                if (!isNetFx) return string.Empty;


                //尝试获取 .Net Framework 的 XML注释文件 路径

                string progFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                string progFolderX86 = progFolder + " (x86)";
                if (Directory.Exists(progFolderX86)) progFolder = progFolderX86;
                if (!Directory.Exists(progFolder)) progFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                string netFxRootFolder = progFolder.TrimEnd('/', '\\') + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\";
                if (!Directory.Exists(netFxRootFolder)) return string.Empty;

                CultureInfo cultCu = CultureInfo.CurrentCulture;
                CultureInfo cultEn = CultureInfo.GetCultureInfo("en-US");
                List<string> listCult = new List<string>();
                listCult.Add(cultCu.Name);
                listCult.Add(cultCu.Parent.Name);
                listCult.Add(cultCu.Parent.Parent.Name);
                listCult.Add(cultEn.Name);
                listCult.Add(cultEn.Parent.Name);
                listCult.Add(cultEn.Parent.Parent.Name);

                string startMajor = "v" + Environment.Version.Major;
                DirectoryInfo rootFolderInfo = new DirectoryInfo(netFxRootFolder);
                List<DirectoryInfo> netMajorFolders = new List<DirectoryInfo>(rootFolderInfo.GetDirectories());
                netMajorFolders.Sort((x, y) => { return StringComparer.InvariantCultureIgnoreCase.Compare(y.Name, x.Name); });

                List<string> listMajorFolder = new List<string>();
                List<string> listMajorFolder2 = new List<string>();
                foreach (DirectoryInfo folder in netMajorFolders)
                    if (folder.Name.StartsWith(startMajor, StringComparison.InvariantCultureIgnoreCase)) listMajorFolder.Add(folder.Name);
                    else listMajorFolder2.Add(folder.Name);
                listMajorFolder.AddRange(listMajorFolder2);


                //此时的 listMajorFolder listCult 都已经按照优先级 降序排列, 优先找到的 即为最适合的. 
                foreach (string folder in listMajorFolder)
                    foreach (string cult in listCult)
                    {
                        string maybePath = netFxRootFolder.TrimEnd('/', '\\') + "\\" + folder + "\\" + cult + "\\" + xmlName;
                        if (File.Exists(maybePath)) return maybePath;
                    }

                return string.Empty;
            }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (Exception) { return string.Empty; }
        }
        private static void InvokeLibSummaryXml(object obj, ActionInvokeLibSummaryXml action)
        {
            try
            {
                LibSummaryXmlInfo libXml = InitLibXml(obj);
                if (libXml == null || libXml.AssemblyXml == null) return;
                if (action != null) action(libXml.AssemblyXml);
            }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (Exception ex) { Tools.LogWarn(ex); }
        }
        private static string FormatSummary(string summary)
        {
            if (Tools.IsNullOrWhiteSpace(summary)) return (summary ?? string.Empty);
            try
            {
                summary = regSummaryFormat.Replace(summary, m => regSummaryFormatRef.Match(m.Value).Value);
                return summary;
            }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (Exception) { return summary; }
        }

        private delegate void ActionInvokeLibSummaryXml(XmlDocument xmlDoc/*, XmlNode node*/);
        private class LibSummaryXmlInfo
        {
            public LibSummaryXmlInfo(Assembly assem, XmlDocument xmlDoc)
            {
                this.Assembly = assem;
                this.AssemblyXml = xmlDoc;
                this.LastRead = DateTime.Now;
            }
            public Assembly Assembly { get; set; }
            public XmlDocument AssemblyXml { get; set; }
            public DateTime LastRead { get; set; }
        }


        #endregion



        #region  反 射 程 序 集

        private static readonly object listAssemblyLocker = new object();
        private static readonly List<Assembly> listAssembly = new List<Assembly>();

        #region  当 前 所 有 程 序 集

        /// <summary>
        /// 获取 程序加载的、或 运行目录的、或 手动调用 Load 函数加载 程序集
        /// </summary>
        public static Assembly[] GetCurrentAssemblies()
        {
            List<Assembly> list = new List<Assembly>();

            if (listAssembly != null && listAssembly.Count >= 1)
                lock (listAssemblyLocker)
                {
                    foreach (Assembly assembly in listAssembly)
                    {
                        try
                        {
                            if (list.Contains(assembly)) list.Remove(assembly);
                            list.Add(assembly);
                        }
                        catch (System.Threading.ThreadAbortException) { throw; }
                        catch (Exception ex) { Tools.LogWarn(ex); }
                    }
                }

#if (!WindowsCE && !PocketPC)
            Assembly[] assemblyArray = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assembly in assemblyArray)
            {
                if (list.Contains(assembly)) list.Remove(assembly);
                list.Add(assembly);
            }
#endif


            List<string> listExeOrDllFile = new List<string>();

            string appDirectory = Tools.AppFolder;
            string appBinDirectory = string.Format(@"{0}\Bin\", appDirectory.TrimEnd('\\', '/'));
            string[] dllFiles = Directory.GetFiles(appDirectory, "*.dll");
            string[] exeFiles = Directory.GetFiles(appDirectory, "*.exe");
            listExeOrDllFile.AddRange(dllFiles);
            listExeOrDllFile.AddRange(exeFiles);

            if (Directory.Exists(appBinDirectory))
            {
                string[] binDllFiles = Directory.GetFiles(appBinDirectory, "*.dll");
                string[] binExeFiles = Directory.GetFiles(appBinDirectory, "*.exe");
                listExeOrDllFile.AddRange(binDllFiles);
                listExeOrDllFile.AddRange(binExeFiles);
            }
            
            lock (listAssemblyLocker)
            {
                foreach (string exeOrDllFile in listExeOrDllFile)
                {
                    try
                    {
                        Assembly assembly = ReflectHelper.Load(Path.GetFileNameWithoutExtension(exeOrDllFile));
                        if (list.Contains(assembly)) list.Remove(assembly);
                        list.Add(assembly);
                    }
                    catch (System.Threading.ThreadAbortException) { throw; }
                    catch (Exception ex) { Tools.LogWarn(ex); }
                }
            }

            return list.ToArray();
        }

        /// <summary>
        /// 往当前程序中添加程序集
        /// </summary>
        public static Assembly Load(string typeName)
        {
            Assembly assembly = Assembly.Load(typeName);
            if (assembly == null) return null;

            if(listAssembly.Contains(assembly)) listAssembly.Remove(assembly);
            listAssembly.Add(assembly);
            return assembly;
        }

        #endregion


        #region  特 性 高 级 用 法

        /// <summary>
        /// 查找所有程序集，获取 所有指定的类特性 T 的 类Type；
        /// </summary>
        public static Dictionary<Type, T> GetAttributes<T>() where T : Attribute
        {
            Assembly[] allAssemblys = GetCurrentAssemblies();
            return GetAttributes<T>(allAssemblys);
        }
        /// <summary>
        /// 查找指定程序集，获取 所有指定的类特性 T 的 类Type；
        /// </summary>
        public static Dictionary<Type, T> GetAttributes<T>(IEnumerable<Assembly> allAssemblys) where T : Attribute
        {
            Dictionary<Type, T> list = new Dictionary<Type, T>();

            if (allAssemblys != null)
            {
                foreach (Assembly assembly in allAssemblys/*listAssembly*/)
                {
                    try
                    {
                        List<Type> types = GetListType(assembly);
                        foreach (Type type in types)
                        {
                            try
                            {
                                if (type.IsDefined(typeof(T), false))
                                {
                                    Attribute attribute = Attribute.GetCustomAttribute(type, typeof(T), false);
                                    if (attribute != null)
                                    {
                                        T wtattri = (T)attribute;
                                        list.Add(type, wtattri);
                                    }
                                }
                            }
                            catch (Exception exp)
                            {
                                string logMsg = string.Format("ReflectHelper.GetAttributes<T>(IEnumerable<Assembly> allAssemblys) 反射程序集 {0} 时发生错误,请确保程序集文件是正确的, ReflectHelper 将跳过该程序集.\r\n异常信息:\r\n{1}", assembly.FullName, exp);
                                Tools.LogWarn(logMsg);
                            }
                        }
                    }
                    catch (System.Threading.ThreadAbortException) { throw; }
                    catch (Exception exp)
                    {
                        string logMsg = string.Format("ReflectHelper.GetAttributes<T>(IEnumerable<Assembly> allAssemblys) 反射程序集 {0} 时发生错误,请确保程序集文件是正确的, ReflectHelper 将跳过该程序集.\r\n异常信息:\r\n{1}", assembly.FullName, exp);
                        Tools.LogWarn(logMsg);
                    }
                }
            }

            return list;
        }


        /// <summary>
        /// 查找指定程序集，获取 所有指定的 函数特性 T 的 函数信息；
        /// </summary>
        public static Dictionary<MethodInfo, T> GetMethodAttributes<T>() where T : Attribute
        {
            Assembly[] allAssemblys = GetCurrentAssemblies();
            return GetMethodAttributes<T>(allAssemblys);
        }
        /// <summary>
        /// 查找指定程序集，获取 所有指定的 函数特性 T 的 函数信息；
        /// </summary>
        public static Dictionary<MethodInfo, T> GetMethodAttributes<T>(IEnumerable<Assembly> allAssemblys) where T : Attribute
        {
            Dictionary<MethodInfo, T> list = new Dictionary<MethodInfo, T>();

            if (allAssemblys != null)
                foreach (Assembly assembly in allAssemblys)
                {
                    try
                    {
                        List<Type> types = GetListType(assembly);
                        foreach (Type type in types)
                        {
                            try
                            {
                                foreach (MethodInfo method in type.GetMethods())
                                {
                                    if (method.IsDefined(typeof(T), false))
                                    {
                                        Attribute attribute = Attribute.GetCustomAttribute(method, typeof(T), false);
                                        if (attribute != null)
                                        {
                                            T wtattri = (T)attribute;
                                            list.Add(method, wtattri);
                                        }
                                    }
                                }
                            }
                            catch (Exception exp)
                            {
                                string logMsg = string.Format("ReflectHelper.GetAttributes<T>(IEnumerable<Assembly> allAssemblys) 反射程序集 {0} 时发生错误,请确保程序集文件是正确的, ReflectHelper 将跳过该程序集.\r\n异常信息:\r\n{1}", assembly.FullName, exp);
                                Tools.LogWarn(logMsg);
                            }
                        }
                    }
                    catch (System.Threading.ThreadAbortException) { throw; }
                    catch (Exception exp)
                    {
                        string logMsg = string.Format("ReflectHelper.GetMethodAttributes<T>(IEnumerable<Assembly> allAssemblys) 反射程序集 {0} 时发生错误,请确保程序集文件是正确的, ReflectHelper 将跳过该程序集.\r\n异常信息:\r\n{1}", assembly.FullName, exp);
                        Tools.LogWarn(logMsg);
                    }
                }

            return list;
        }
        /// <summary>
        /// 查找指定程序集，获取 所有指定的 函数特性 T 的 函数信息；
        /// </summary>
        public static Dictionary<MethodInfo, T> GetMethodAttributes<T>(Type type) where T : Attribute
        {
            Dictionary<MethodInfo, T> list = new Dictionary<MethodInfo, T>();

            if (type != null)
                try
                {
                    foreach (MethodInfo method in type.GetMethods())
                    {
                        try
                        {
                            if (method.IsDefined(typeof(T), false))
                            {
                                Attribute attribute = Attribute.GetCustomAttribute(method, typeof(T), false);
                                if (attribute != null)
                                {
                                    T wtattri = (T)attribute;
                                    list.Add(method, wtattri);
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            string logMsg = string.Format("ReflectHelper.GetMethodAttributes<T>(Type type) 反射类型 {0} 时发生错误.\r\n异常信息:\r\n{1}", type.FullName, exp);
                            Tools.LogWarn(logMsg);
                        }
                    }
                }
                catch (System.Threading.ThreadAbortException) { throw; }
                catch (Exception exp)
                {
                    string logMsg = string.Format("ReflectHelper.GetMethodAttributes<T>(Type type) 反射类型 {0} 时发生错误.\r\n异常信息:\r\n{1}", type.FullName, exp);
                    Tools.LogWarn(logMsg);
                }

            return list;
        }

        #endregion

        public static Type FindBaseType(Type sourceType, Type findType)
        {
            if (sourceType == null) return null;

#if (!WindowsCE && !PocketPC)
            bool baseTypeIsSame = sourceType.GUID == findType.GUID;
#endif
#if (WindowsCE || PocketPC)
            bool baseTypeIsSame = (sourceType.Namespace + "." + sourceType.Name) == (findType.Namespace + "." + findType.Name);
#endif
            if (baseTypeIsSame) return sourceType;

            //基类 继承链
            Type baseType = sourceType.BaseType;
            Type findBaseType = FindBaseType(baseType, findType);
            if (findBaseType != null) return findBaseType;

            //接口 继承链
            Type[] interfaceTypes = sourceType.GetInterfaces();
            if (interfaceTypes.Length > 0)
                foreach (Type interfaceType in interfaceTypes)
                {
                    Type findInterfaceBaseType = FindBaseType(interfaceType, findType);
                    if (findInterfaceBaseType != null) return findInterfaceBaseType;
                }

            return null;
        }

        /// <summary>
        /// 获取指定程序集中的 所有类型, 本函数 比 Assembly.GetTypes() 优势在于: 本函数在失败时 能给出 详细的异常提示.
        /// </summary>
        public static List<Type> GetListType(Assembly assembly)
        {
            if (assembly == null) return null;

            try
            {
                Type[] types = assembly.GetTypes();
                return new List<Type>(types);
            }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (Exception exp)
            {
#if (!WindowsCE && !PocketPC)
                List<AssemblyName> listErrorRefAssembly = GetListErrorRefAssembly(assembly);
                AssemblyName[] refMissAssemblies = listErrorRefAssembly == null ? new AssemblyName[0] : listErrorRefAssembly.ToArray();
                throw AssemblyMissException.Create(assembly, refMissAssemblies, exp);
#endif
#if (WindowsCE || PocketPC)
                throw;
#endif           
            }
        }

#if (!WindowsCE && !PocketPC)

        /// <summary>
        /// 获取指定程序集 引用的 程序集集合
        /// </summary>
        public static List<AssemblyName> GetListRefAssembly(Assembly assembly)
        {
            AssemblyName[] refAssemblies = assembly.GetReferencedAssemblies();
            List<AssemblyName> listResult = new List<AssemblyName>(refAssemblies);
            return listResult;
        }
        /// <summary>
        /// 获取指定程序集 依赖但是无法加载的 程序集集合
        /// </summary>
        public static List<AssemblyName> GetListErrorRefAssembly(Assembly assembly)
        {
            List<AssemblyName> listRefAssembly = GetListRefAssembly(assembly);
            if (listRefAssembly == null) return null;

            Assembly[] listCurrAssembly = GetCurrentAssemblies();
            IgnoreDict<Assembly> hashCurrAssembly = new IgnoreDict<Assembly>();
            foreach (Assembly item in listCurrAssembly)
                hashCurrAssembly[item.FullName] = item;

            List<AssemblyName> listErrorRefAssembly = new List<AssemblyName>();
            foreach (AssemblyName item in listRefAssembly)
            {
                if (!hashCurrAssembly.ContainsKey(item.FullName))
                {
                    bool find = TryFindAssemblyByFullName(item);
                    if (!find) listErrorRefAssembly.Add(item);
                }
            }
            return listErrorRefAssembly;
        }

#endif

        /// <summary>
        /// 尝试 从 全局GAC 或 当前程序 运行目录, 判断指定的程序集全名 是否存在.
        /// </summary>
        public static bool TryFindAssemblyByFullName(AssemblyName assemblyName)
        {
            try { Assembly.Load(assemblyName); return true; }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (Exception) { return false; }
        }


        /// <summary>
        /// 通过父类型, 反射出 所有子类型
        /// </summary>
        public static List<Type> GetTypes(Type parentType)
        {
            Assembly[] allAssemblys = GetCurrentAssemblies();
            return GetTypes(allAssemblys, parentType);
        }
        /// <summary>
        /// 通过父类型, 反射出 所有子类型
        /// </summary>
        public static List<Type> GetTypes(IEnumerable<Assembly> allAssemblys, Type parentType)
        {
            List<Type> list = new List<Type>();

            if (allAssemblys != null)
                foreach (Assembly assembly in allAssemblys/*listAssembly*/)
                {
                    try
                    {
                        List<Type> types = GetListType(assembly);
                        foreach (Type type in types)
                        {
                            if (parentType.IsAssignableFrom(type))
                                list.Add(type);
                        }
                    }
                    catch (System.Threading.ThreadAbortException) { throw; }
                    catch (Exception exp)
                    {
#if (!WindowsCE && !PocketPC)
                        string logMsg = string.Format("ReflectHelper.GetTypes<T>(IEnumerable<Assembly> allAssemblys, Type parentType) 反射程序集 {0} 时发生错误,请确保程序集文件是正确的, ReflectHelper 将跳过该程序集:\r\n{1}", assembly.FullName, exp);
                        Tools.LogWarn(logMsg);
#endif
                    }
                }

            return list;

        }

        /// <summary>
        /// 判断指定的 属性是否是 静态属性
        /// </summary>
        public static bool IsStaticPropertyInfo(PropertyInfo property)
        {
            if (property == null) return false;
            MethodInfo methodGet = property.GetGetMethod();
            if (methodGet != null) return methodGet.IsStatic;

            MethodInfo methodSet = property.GetSetMethod();
            if (methodSet != null) return methodSet.IsStatic;

            return false;
        }


        #endregion



        #region  动 态 构 建 Emit 函 数

#if (!WindowsCE && !PocketPC)
        public static Delegate CreateEmitMethod(MethodInfo method)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(null, method, null, null);
            return result;
        }
        public static Delegate CreateEmitGenericMethod(MethodInfo method, Type[] methodGenericTypes)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(null, method, null, methodGenericTypes);
            return result;
        }
        public static Delegate CreateEmitGenericMethod(MethodInfo method, Type[] classGenericTypes, Type[] methodGenericTypes)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(null, method, classGenericTypes, methodGenericTypes);
            return result;
        }
        public static Delegate CreateEmitMethod(Type defineType, MethodInfo method)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(defineType, method, null, null);
            return result;
        }
        public static Delegate CreateEmitGenericMethod(Type defineType, MethodInfo method, Type[] methodGenericTypes)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(defineType, method, null, methodGenericTypes);
            return result;
        }
        public static Delegate CreateEmitMethod<ActionOrFuncDefine>(MethodInfo method)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(typeof(ActionOrFuncDefine), method, null, null);
            return result;
        }
        public static Delegate CreateEmitGenericMethod<ActionOrFuncDefine>(MethodInfo method, Type[] methodGenericTypes)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(typeof(ActionOrFuncDefine), method, null, methodGenericTypes);
            return result;
        }
        public static Delegate CreateEmitGenericMethod<ActionOrFuncDefine>(MethodInfo method, Type[] classGenericTypes, Type[] methodGenericTypes)
        {
            if (method == null) return null;
            Delegate result = CreateEmitGenericMethod(typeof(ActionOrFuncDefine), method, classGenericTypes, methodGenericTypes);
            return result;
        }
        public static Delegate CreateEmitGenericMethod(Type defineType, MethodInfo method, Type[] classGenericTypes, Type[] methodGenericTypes)
        {
            if (method == null) return null;

            ReflectMethodInfo methodInfo = ReflectMethodInfo.Create(method, classGenericTypes, methodGenericTypes);
            int paramCount = methodInfo.ParamTypesCount;

            Type define = defineType;
            if (define == null)
            {
                #region  基 础 类 型
                if (methodInfo.IsAction)
                {
                    if (paramCount == 0)        define = typeof(EmitAction);
                    else if (paramCount == 1)   define = typeof(EmitAction<>);
                    else if (paramCount == 2)   define = typeof(EmitAction<,>);
                    else if (paramCount == 3)   define = typeof(EmitAction<,,>);
                    else if (paramCount == 4)   define = typeof(EmitAction<,,,>);
                    else if (paramCount == 5)   define = typeof(EmitAction<,,,,>);
                    else if (paramCount == 6)   define = typeof(EmitAction<,,,,,>);
                    else if (paramCount == 7)   define = typeof(EmitAction<,,,,,,>);
                    else if (paramCount == 8)   define = typeof(EmitAction<,,,,,,,>);
                    else if (paramCount == 9)   define = typeof(EmitAction<,,,,,,,,>);
                    else if (paramCount == 10)  define = typeof(EmitAction<,,,,,,,,,>);
                    else if (paramCount == 11)  define = typeof(EmitAction<,,,,,,,,,,>);
                    else if (paramCount == 12)  define = typeof(EmitAction<,,,,,,,,,,,>);
                    else if (paramCount == 13)  define = typeof(EmitAction<,,,,,,,,,,,,>);
                    else if (paramCount == 14)  define = typeof(EmitAction<,,,,,,,,,,,,,>);
                    else if (paramCount == 15)  define = typeof(EmitAction<,,,,,,,,,,,,,,>);
                    else if (paramCount == 16)  define = typeof(EmitAction<,,,,,,,,,,,,,,,>);
                }
                else
                {
                    if (paramCount == 0)        define = typeof(EmitFunc<>);
                    else if (paramCount == 1)   define = typeof(EmitFunc<,>);
                    else if (paramCount == 2)   define = typeof(EmitFunc<,,>);
                    else if (paramCount == 3)   define = typeof(EmitFunc<,,,>);
                    else if (paramCount == 4)   define = typeof(EmitFunc<,,,,>);
                    else if (paramCount == 5)   define = typeof(EmitFunc<,,,,,>);
                    else if (paramCount == 6)   define = typeof(EmitFunc<,,,,,,>);
                    else if (paramCount == 7)   define = typeof(EmitFunc<,,,,,,,>);
                    else if (paramCount == 8)   define = typeof(EmitFunc<,,,,,,,,>);
                    else if (paramCount == 9)   define = typeof(EmitFunc<,,,,,,,,,>);
                    else if (paramCount == 10)  define = typeof(EmitFunc<,,,,,,,,,,>);
                    else if (paramCount == 11)  define = typeof(EmitFunc<,,,,,,,,,,,>);
                    else if (paramCount == 12)  define = typeof(EmitFunc<,,,,,,,,,,,,>);
                    else if (paramCount == 13)  define = typeof(EmitFunc<,,,,,,,,,,,,,>);
                    else if (paramCount == 14)  define = typeof(EmitFunc<,,,,,,,,,,,,,,>);
                    else if (paramCount == 15)  define = typeof(EmitFunc<,,,,,,,,,,,,,,,>);
                    else if (paramCount == 16)  define = typeof(EmitFunc<,,,,,,,,,,,,,,,,>);
                }
                #endregion

                if (define == null) return null;

                #region  完 善 参 数

                if (methodInfo.IsAction)
                    define = define.MakeGenericType(methodInfo.ParamTypes.ToArray());
                else
                    define = define.MakeGenericType(methodInfo.ParamAndReturnTypes.ToArray());

                #endregion
            }

            Delegate result = BuildEmitMethodIL(method, define, methodInfo, classGenericTypes, methodGenericTypes);
            return result;
        }



        internal static Delegate BuildEmitMethodIL(MethodInfo method, Type define, ReflectMethodInfo methodInfo, Type[] classGenericTypes, Type[] methodGenericTypes)
        {
            if (define == null || method == null) return null;
            if (methodInfo == null) methodInfo = ReflectMethodInfo.Create(method, classGenericTypes, methodGenericTypes);

            DynamicMethod dm = new DynamicMethod("Emit_" + method.Name, methodInfo.ReturnType, methodInfo.ParamTypes.ToArray(), methodInfo.DeclaringType, true);
            ILGenerator generator = dm.GetILGenerator();
            //generator.Emit(OpCodes.Nop);

            if (methodInfo.IsStatic)
            {
                //将参数压栈
                for (int i = 0, count = methodInfo.ParamTypesCount; i < count; i++)
                    generator.Emit(OpCodes.Ldarg, i);

                //调用静态函数
                generator.Emit(OpCodes.Call, methodInfo.Method);
                if (methodInfo.IsAction)
                {
                    generator.Emit(OpCodes.Nop);
                }
                else
                {
                    //generator.Emit(OpCodes.Stloc_0);
                    //generator.Emit(OpCodes.Ldloc_0);
                    //generator.Emit(OpCodes.Box, typeof(object));  //装箱
                    //if (method.ReturnType != typeof(object))
                    //    generator.Emit(OpCodes.Unbox, method.ReturnType);  //拆箱
                }
                generator.Emit(OpCodes.Ret);
            }
            else
            {
                //将参数压栈
                generator.Emit(OpCodes.Ldarg, 0); //成员函数第一个成员是 实体本身
                for (int i = 1, count = methodInfo.ParamTypesCount; i < count; i++)
                    generator.Emit(OpCodes.Ldarg, i);

                //调用成员函数
                generator.Emit(OpCodes.Callvirt, methodInfo.Method);
                if (methodInfo.IsAction)
                {
                    generator.Emit(OpCodes.Nop);
                }
                else
                {
                    //generator.Emit(OpCodes.Stloc_0);
                    //generator.Emit(OpCodes.Ldloc_0);
                    //generator.Emit(OpCodes.Box, typeof(object));  //装箱
                    //if (method.ReturnType != typeof(object))
                    //    generator.Emit(OpCodes.Unbox, method.ReturnType);  //拆箱
                }
                generator.Emit(OpCodes.Ret);
            }

            Delegate emitMethod = dm.CreateDelegate(define);
            return emitMethod;
        }

#endif
        #endregion



        #region  动 态 赋 取 值

        internal const BindingFlags Property_Field_BindingFlags = BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
        
        #region  动 态 赋 值

        private static SetValueTypeEnum currentSetValueTypeEnum = SetValueTypeEnum.None;
        internal static SetValueTypeEnum CurrentSetValueTypeEnum
        {
            get
            {
#if (!WindowsCE && !PocketPC)
                if (currentSetValueTypeEnum == SetValueTypeEnum.None)
                    currentSetValueTypeEnum = string.Equals(ConfigurationManager.AppSettings["ReflectHelper_SetValueType"], "Reflect", StringComparison.CurrentCultureIgnoreCase)
                            ? SetValueTypeEnum.Reflect
                            : SetValueTypeEnum.Emit;

                return currentSetValueTypeEnum;
#endif
#if (WindowsCE || PocketPC)
                return SetValueTypeEnum.Reflect;
#endif
            }
        }

#if (!WindowsCE && !PocketPC)

        #region  Emit 委 托 赋 值

        internal static SetValueDelegate InnerEmitCreateSetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null || propertyInfo.PropertyType == null || !propertyInfo.CanWrite) return null;
            MethodInfo setMethod = propertyInfo.GetSetMethod(true);
            if (setMethod == null) return null;

            Type propertyType = propertyInfo.PropertyType;

            DynamicMethod dm = new DynamicMethod("SetPropertyValue", null, new[] { typeof(object), typeof(object) }, propertyInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldarg_1);
            generator.Emit(propertyType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, propertyType);  //拆箱
            generator.Emit(OpCodes.Callvirt, setMethod);
            generator.Emit(OpCodes.Nop);
            generator.Emit(OpCodes.Ret);

            return (SetValueDelegate)dm.CreateDelegate(typeof(SetValueDelegate));
        }
        internal static SetValueDelegate InnerEmitCreateSetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null || fieldInfo.FieldType == null || fieldInfo.IsStatic || fieldInfo.IsInitOnly || fieldInfo.IsLiteral) return null;

            Type fieldType = fieldInfo.FieldType;

            DynamicMethod dm = new DynamicMethod("SetFieldValue", null, new[] { typeof(object), typeof(object) }, fieldInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldarg_1);
            generator.Emit(fieldType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, fieldType);  //拆箱
            generator.Emit(OpCodes.Stfld, fieldInfo);
            generator.Emit(OpCodes.Ret);

            return (SetValueDelegate)dm.CreateDelegate(typeof(SetValueDelegate));
        }
        internal static StaticSetValueDelegate InnerEmitCreateStaticSetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null || propertyInfo.PropertyType == null || !propertyInfo.CanWrite) return null;
            MethodInfo setMethod = propertyInfo.GetSetMethod(true);
            if (setMethod == null) return null;

            Type propertyType = propertyInfo.PropertyType;

            DynamicMethod dm = new DynamicMethod("StaticSetPropertyValue", null, new [] { typeof(object) }, propertyInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(propertyType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, propertyType);  //拆箱
            generator.Emit(OpCodes.Call, setMethod);
            generator.Emit(OpCodes.Nop);
            generator.Emit(OpCodes.Ret);

            return (StaticSetValueDelegate)dm.CreateDelegate(typeof(StaticSetValueDelegate));
        }
        internal static StaticSetValueDelegate InnerEmitCreateStaticSetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null || fieldInfo.FieldType == null || !fieldInfo.IsStatic || fieldInfo.IsInitOnly || fieldInfo.IsLiteral) return null;

            Type fieldType = fieldInfo.FieldType;

            DynamicMethod dm = new DynamicMethod("StaticSetFieldValue", null, new[] { typeof(object) }, fieldInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(fieldType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, fieldType);  //拆箱
            generator.Emit(OpCodes.Stsfld, fieldInfo);
            generator.Emit(OpCodes.Ret);

            return (StaticSetValueDelegate)dm.CreateDelegate(typeof(StaticSetValueDelegate));
        }

        private static readonly Hashtable setPropertyValueDelegates = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable setFieldValueDelegates = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable setStaticPropertyValueDelegates = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable setStaticFieldValueDelegates = Hashtable.Synchronized(new Hashtable());

        public static SetValueDelegate CreateEmitSetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null) return null;

            SetValueDelegate setValueDelegate = setPropertyValueDelegates[propertyInfo] as SetValueDelegate;
            if (setValueDelegate == null)
            {
                setValueDelegate = InnerEmitCreateSetValueDelegate(propertyInfo);
                setPropertyValueDelegates[propertyInfo] = setValueDelegate;
            }
            return setValueDelegate;
        }
        public static SetValueDelegate CreateEmitSetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null) return null;

            SetValueDelegate setValueDelegate = setFieldValueDelegates[fieldInfo] as SetValueDelegate;
            if (setValueDelegate == null)
            {
                setValueDelegate = InnerEmitCreateSetValueDelegate(fieldInfo);
                setFieldValueDelegates[fieldInfo] = setValueDelegate;
            }
            return setValueDelegate;
        }
        public static StaticSetValueDelegate CreateEmitStaticSetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null) return null;

            StaticSetValueDelegate setValueDelegate = setStaticPropertyValueDelegates[propertyInfo] as StaticSetValueDelegate;
            if (setValueDelegate == null)
            {
                setValueDelegate = InnerEmitCreateStaticSetValueDelegate(propertyInfo);
                setStaticPropertyValueDelegates[propertyInfo] = setValueDelegate;
            }
            return setValueDelegate;
        }
        public static StaticSetValueDelegate CreateEmitStaticSetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null) return null;

            StaticSetValueDelegate setValueDelegate = setStaticFieldValueDelegates[fieldInfo] as StaticSetValueDelegate;
            if (setValueDelegate == null)
            {
                setValueDelegate = InnerEmitCreateStaticSetValueDelegate(fieldInfo);
                setStaticFieldValueDelegates[fieldInfo] = setValueDelegate;
            }
            return setValueDelegate;
        }


        public static bool EmitSetValue(object target, string propertyOrFieldName, object value)
        {
            if (target == null || string.IsNullOrEmpty(propertyOrFieldName)) return false;

            Type type = target.GetType();
            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return EmitSetValue(target, propertyInfo, value);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null)
                    return EmitSetValue(target, fieldInfo, value);
            }

            return false;
        }
        public static bool EmitSetStaticValue(Type type, string propertyOrFieldName, object value)
        {
            if (type == null || string.IsNullOrEmpty(propertyOrFieldName)) return false;

            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return EmitSetStaticValue(propertyInfo, value);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null)
                    return EmitSetStaticValue(fieldInfo, value);
            }

            return false;
        }
        public static bool EmitSetValue(object target, PropertyInfo propertyInfo, object value)
        {
            if (target == null || propertyInfo == null || !propertyInfo.CanWrite) return false;

            if (IsStaticPropertyInfo(propertyInfo))
            {
                return EmitSetStaticValue(propertyInfo, value);
            }
            else
            {
                SetValueDelegate setter = CreateEmitSetValueDelegate(propertyInfo);
                if (setter != null)
                {
                    object newValue = ChangeType(value, propertyInfo.PropertyType);
                    setter(target, newValue);
                    return true;
                }
            }

            return false;
        }
        public static bool EmitSetStaticValue(PropertyInfo propertyInfo, object value)
        {
            if (propertyInfo == null || !propertyInfo.CanWrite) return false;

            StaticSetValueDelegate setter = CreateEmitStaticSetValueDelegate(propertyInfo);
            if (setter != null)
            {
                object newValue = ChangeType(value, propertyInfo.PropertyType);
                setter(newValue);
                return true;
            }

            return false;
        }
        public static bool EmitSetValue(object target, FieldInfo fieldInfo, object value)
        {
            if (target == null || fieldInfo == null || fieldInfo.IsInitOnly || fieldInfo.IsLiteral) return false;

            if (fieldInfo.IsStatic)
            {
                return EmitSetStaticValue(fieldInfo, value);
            }
            else
            {
                SetValueDelegate setter = CreateEmitSetValueDelegate(fieldInfo);
                if (setter != null)
                {
                    object newValue = ChangeType(value, fieldInfo.FieldType);
                    setter(target, newValue);
                    return true;
                }
            }

            return false;
        }
        public static bool EmitSetStaticValue(FieldInfo fieldInfo, object value)
        {
            if (fieldInfo == null || fieldInfo.IsInitOnly || fieldInfo.IsLiteral) return false;

            StaticSetValueDelegate setter = CreateEmitStaticSetValueDelegate(fieldInfo);
            if (setter != null)
            {
                object newValue = ChangeType(value, fieldInfo.FieldType);
                setter(newValue);
                return true;
            }

            return false;
        }

        #endregion

#endif


        #region  纯 反 射 赋 值

        public static bool ReflectSetValue(object target, string propertyOrFieldName, object value)
        {
            if (target == null || string.IsNullOrEmpty(propertyOrFieldName)) return false;

            Type type = target.GetType();
            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return ReflectSetValue(target, propertyInfo, value);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null)
                    return ReflectSetValue(target, fieldInfo, value);
            }

            return false;
        }
        public static bool ReflectSetStaticValue(Type type, string propertyOrFieldName, object value)
        {
            if (type == null || string.IsNullOrEmpty(propertyOrFieldName)) return false;

            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return ReflectSetStaticValue(propertyInfo, value);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null)
                    return ReflectSetStaticValue(fieldInfo, value);
            }

            return false;
        }
        public static bool ReflectSetValue(object target, PropertyInfo propertyInfo, object value)
        {
            if (target == null || propertyInfo == null || !propertyInfo.CanWrite) return false;

            object newValue = ChangeType(value, propertyInfo.PropertyType);
            propertyInfo.SetValue(target, newValue, null);
            return true;
        }
        public static bool ReflectSetStaticValue(PropertyInfo propertyInfo, object value)
        {
            if (propertyInfo == null || !propertyInfo.CanWrite) return false;

            object newValue = ChangeType(value, propertyInfo.PropertyType);
            propertyInfo.SetValue(null, newValue, null);
            return true;
        }
        public static bool ReflectSetValue(object target, FieldInfo fieldInfo, object value)
        {
            if (target == null || fieldInfo == null || fieldInfo.IsInitOnly || fieldInfo.IsLiteral) return false;

            object newValue = ChangeType(value, fieldInfo.FieldType);
            fieldInfo.SetValue(target, newValue);
            return true;
        }
        public static bool ReflectSetStaticValue(FieldInfo fieldInfo, object value)
        {
            if (fieldInfo == null || fieldInfo.IsInitOnly || fieldInfo.IsLiteral) return false;

            object newValue = ChangeType(value, fieldInfo.FieldType);
            fieldInfo.SetValue(null, newValue);
            return true;
        }
        
        #endregion

        /// <summary>
        /// 动态为 某个对象的属性 赋值，本函数不支持 多级赋值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static bool SetValue(object target, string propertyOrFieldName, object value)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentSetValueTypeEnum)
            {
                case SetValueTypeEnum.Emit:
                    return EmitSetValue(target, propertyOrFieldName, value);
                default:
                    return ReflectSetValue(target, propertyOrFieldName, value);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectSetValue(target, propertyOrFieldName, value);
#endif
        }
        /// <summary>
        /// 动态为 某个类的静态属性 赋值，本函数不支持 多级赋值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static bool SetStaticValue(Type type, string propertyOrFieldName, object value)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentSetValueTypeEnum)
            {
                case SetValueTypeEnum.Emit:
                    return EmitSetStaticValue(type, propertyOrFieldName, value);
                default:
                    return ReflectSetStaticValue(type, propertyOrFieldName, value);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectSetStaticValue(type, propertyOrFieldName, value);
#endif
        }
        /// <summary>
        /// 动态为 某个对象的属性 赋值，本函数不支持 多级赋值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static bool SetValue(object target, PropertyInfo propertyInfo, object value)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentSetValueTypeEnum)
            {
                case SetValueTypeEnum.Emit:
                    return EmitSetValue(target, propertyInfo, value);
                default:
                    return ReflectSetValue(target, propertyInfo, value);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectSetValue(target, propertyInfo, value);
#endif
        }
        /// <summary>
        /// 动态为 某个类的静态属性 赋值，本函数不支持 多级赋值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static bool SetStaticValue(Type type, PropertyInfo propertyInfo, object value)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentSetValueTypeEnum)
            {
                case SetValueTypeEnum.Emit:
                    return EmitSetStaticValue(propertyInfo, value);
                default:
                    return ReflectSetStaticValue(propertyInfo, value);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectSetStaticValue(propertyInfo, value);
#endif
        }
        /// <summary>
        /// 动态为 某个对象的属性 赋值，本函数不支持 多级赋值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static bool SetValue(object target, FieldInfo fieldInfo, object value)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentSetValueTypeEnum)
            {
                case SetValueTypeEnum.Emit:
                    return EmitSetValue(target, fieldInfo, value);
                default:
                    return ReflectSetValue(target, fieldInfo, value);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectSetValue(target, fieldInfo, value);
#endif
        }
        /// <summary>
        /// 动态为 某个类的静态属性 赋值，本函数不支持 多级赋值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static bool SetStaticValue(FieldInfo fieldInfo, object value)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentSetValueTypeEnum)
            {
                case SetValueTypeEnum.Emit:
                    return EmitSetStaticValue(fieldInfo, value);
                default:
                    return ReflectSetStaticValue(fieldInfo, value);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectSetStaticValue(fieldInfo, value);
#endif
        }

        #endregion

        #region  动 态 取 值

#if (!WindowsCE && !PocketPC)
        private static GetValueTypeEnum currentGetValueTypeEnum = GetValueTypeEnum.None;
#endif
        internal static GetValueTypeEnum CurrentGetValueTypeEnum
        {
            get
            {
#if (!WindowsCE && !PocketPC)
                if (currentGetValueTypeEnum == GetValueTypeEnum.None)
                    currentGetValueTypeEnum = string.Equals(ConfigurationManager.AppSettings["ReflectHelper_GetValueType"], "Reflect", StringComparison.CurrentCultureIgnoreCase)
                            ? GetValueTypeEnum.Reflect
                            : GetValueTypeEnum.Emit;

                return currentGetValueTypeEnum;
#endif
#if (WindowsCE || PocketPC)
                return GetValueTypeEnum.Reflect;
#endif
            }
        }

#if (!WindowsCE && !PocketPC)

        #region  Emit 委 托 取 值

        internal static GetValueDelegate InnerEmitCreateGetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null || propertyInfo.PropertyType == null || !propertyInfo.CanRead) return null;
            MethodInfo getMethod = propertyInfo.GetGetMethod(true);
            if (getMethod == null) return null;

            Type propertyType = propertyInfo.PropertyType;

            DynamicMethod dm = new DynamicMethod("GetPropertyValue", typeof(object), new [] { typeof(object) }, propertyInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Callvirt, getMethod);
            //if(propertyType.IsValueType) 
                generator.Emit(OpCodes.Box, propertyType);  //装箱
            generator.Emit(OpCodes.Ret);

            return (GetValueDelegate)dm.CreateDelegate(typeof(GetValueDelegate));
        }
        internal static GetValueDelegate InnerEmitCreateGetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null || fieldInfo.FieldType == null || fieldInfo.IsStatic) return null;

            Type fieldType = fieldInfo.FieldType;

            DynamicMethod dm = new DynamicMethod("GetFieldValue", typeof(object), new[] { typeof(object) }, fieldInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldfld, fieldInfo);
            //if (fieldType.IsValueType) 
                generator.Emit(OpCodes.Box, fieldType);  //装箱
            generator.Emit(OpCodes.Ret);

            return (GetValueDelegate)dm.CreateDelegate(typeof(GetValueDelegate));
        }
        internal static StaticGetValueDelegate InnerEmitCreateStaticGetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null || propertyInfo.PropertyType == null || !propertyInfo.CanRead) return null;
            MethodInfo getMethod = propertyInfo.GetGetMethod(true);
            if (getMethod == null) return null;

            Type propertyType = propertyInfo.PropertyType;

            DynamicMethod dm = new DynamicMethod("StaticGetPropertyValue", typeof(object), new Type[] { }, propertyInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Call, getMethod);
            //if (propertyType.IsValueType) 
                generator.Emit(OpCodes.Box, propertyType);  //装箱
            generator.Emit(OpCodes.Ret);

            return (StaticGetValueDelegate)dm.CreateDelegate(typeof(StaticGetValueDelegate));
        }
        internal static StaticGetValueDelegate InnerEmitCreateStaticGetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null || fieldInfo.FieldType == null || !fieldInfo.IsStatic) return null;

            Type fieldType = fieldInfo.FieldType;

            DynamicMethod dm = new DynamicMethod("StaticGetFieldValue", typeof(object), new Type[] { }, fieldInfo.Module, true);
            ILGenerator generator = dm.GetILGenerator();

            generator.Emit(OpCodes.Ldsfld, fieldInfo);
            //if (fieldType.IsValueType) 
                generator.Emit(OpCodes.Box, fieldType);  //装箱
            generator.Emit(OpCodes.Ret);

            return (StaticGetValueDelegate)dm.CreateDelegate(typeof(StaticGetValueDelegate));
        }

        private static readonly Hashtable getPropertyValueDelegates = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable getFieldValueDelegates = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable getStaticPropertyValueDelegates = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable getStaticFieldValueDelegates = Hashtable.Synchronized(new Hashtable());

        public static GetValueDelegate CreateEmitGetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null) return null;

            GetValueDelegate getValueDelegate = getPropertyValueDelegates[propertyInfo] as GetValueDelegate;
            if (getValueDelegate == null)
            {
                getValueDelegate = InnerEmitCreateGetValueDelegate(propertyInfo);
                getPropertyValueDelegates[propertyInfo] = getValueDelegate;
            }
            return getValueDelegate;
        }
        public static GetValueDelegate CreateEmitGetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null) return null;

            GetValueDelegate getValueDelegate = getFieldValueDelegates[fieldInfo] as GetValueDelegate;
            if (getValueDelegate == null)
            {
                getValueDelegate = InnerEmitCreateGetValueDelegate(fieldInfo);
                getFieldValueDelegates[fieldInfo] = getValueDelegate;
            }
            return getValueDelegate;
        }
        public static StaticGetValueDelegate CreateEmitStaticGetValueDelegate(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null) return null;

            StaticGetValueDelegate getValueDelegate = getStaticPropertyValueDelegates[propertyInfo] as StaticGetValueDelegate;
            if (getValueDelegate == null)
            {
                getValueDelegate = InnerEmitCreateStaticGetValueDelegate(propertyInfo);
                getStaticPropertyValueDelegates[propertyInfo] = getValueDelegate;
            }
            return getValueDelegate;
        }
        public static StaticGetValueDelegate CreateEmitStaticGetValueDelegate(FieldInfo fieldInfo)
        {
            if (fieldInfo == null) return null;

            StaticGetValueDelegate getValueDelegate = getStaticFieldValueDelegates[fieldInfo] as StaticGetValueDelegate;
            if (getValueDelegate == null)
            {
                getValueDelegate = InnerEmitCreateStaticGetValueDelegate(fieldInfo);
                getStaticFieldValueDelegates[fieldInfo] = getValueDelegate;
            }
            return getValueDelegate;
        }


        public static object EmitGetValue(object target, string propertyOrFieldName)
        {
            if (target == null || string.IsNullOrEmpty(propertyOrFieldName)) return null;

            Type type = target.GetType();
            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return EmitGetValue(target, propertyInfo);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null)
                    return EmitGetValue(target, fieldInfo);
            }

            return null;
        }
        public static object EmitGetStaticValue(Type type, string propertyOrFieldName)
        {
            if (type == null || string.IsNullOrEmpty(propertyOrFieldName)) return null;

            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return EmitGetStaticValue(propertyInfo);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null )
                    return EmitGetStaticValue(fieldInfo);
            }

            return null;
        }
        public static object EmitGetValue(object target, PropertyInfo propertyInfo)
        {
            if (target == null || propertyInfo == null || !propertyInfo.CanRead) return null;
            if (IsStaticPropertyInfo(propertyInfo))
            {
                return EmitGetStaticValue(propertyInfo);
            }
            else
            {
                GetValueDelegate getter = CreateEmitGetValueDelegate(propertyInfo);
                return getter != null ? getter(target) : null;
            }
        }
        public static object EmitGetStaticValue(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null || !propertyInfo.CanRead) return null;

            StaticGetValueDelegate getter = CreateEmitStaticGetValueDelegate(propertyInfo);
            return getter != null ? getter() : null;
        }
        public static object EmitGetValue(object target, FieldInfo fieldInfo)
        {
            if (target == null || fieldInfo == null/* || fieldInfo.IsInitOnly || fieldInfo.IsLiteral*/) return null;

            if (fieldInfo.IsStatic)
            {
                return EmitGetStaticValue(fieldInfo);
            }
            else
            {
                GetValueDelegate getter = CreateEmitGetValueDelegate(fieldInfo);
                return getter != null ? getter(target) : null;
            }
        }
        public static object EmitGetStaticValue(FieldInfo fieldInfo)
        {
            if (fieldInfo == null/* || fieldInfo.IsInitOnly || fieldInfo.IsLiteral*/) return null;

            StaticGetValueDelegate getter = CreateEmitStaticGetValueDelegate(fieldInfo);
            return getter != null ? getter() : null;
        }

        #endregion

#endif

        #region  纯 反 射 取 值

        public static object ReflectGetValue(object target, string propertyOrFieldName)
        {
            if (target == null || string.IsNullOrEmpty(propertyOrFieldName)) return null;

            Type type = target.GetType();
            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return ReflectGetValue(target, propertyInfo);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null)
                    return ReflectGetValue(target, fieldInfo);
            }

            return null;
        }
        public static object ReflectGetStaticValue(Type type, string propertyOrFieldName)
        {
            if (type == null || string.IsNullOrEmpty(propertyOrFieldName)) return null;

            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null)
                return ReflectGetStaticValue(propertyInfo);
            else
            {
                FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
                if (fieldInfo != null)
                    return ReflectGetStaticValue(fieldInfo);
            }

            return null;
        }
        public static object ReflectGetValue(object target, PropertyInfo propertyInfo)
        {
            if (target == null || propertyInfo == null || !propertyInfo.CanRead) return null;

            object value = propertyInfo.GetValue(target, null);
            return value;
        }
        public static object ReflectGetStaticValue(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null || !propertyInfo.CanRead) return null;

            object value = propertyInfo.GetValue(null, null);
            return value;
        }
        public static object ReflectGetValue(object target, FieldInfo fieldInfo)
        {
            if (target == null || fieldInfo == null/* || fieldInfo.IsInitOnly || fieldInfo.IsLiteral*/) return null;

            object value = fieldInfo.GetValue(target);
            return value;
        }
        public static object ReflectGetStaticValue(FieldInfo fieldInfo)
        {
            if (fieldInfo == null/* || fieldInfo.IsInitOnly || fieldInfo.IsLiteral*/) return null;

            object value = fieldInfo.GetValue(null);
            return value;
        }

        #endregion

        /// <summary>
        /// 动态从 某个对象的属性 取值，本函数不支持 多级取值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_GetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static object GetValue(object target, string propertyOrFieldName)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentGetValueTypeEnum)
            {
                case GetValueTypeEnum.Emit:
                    return EmitGetValue(target, propertyOrFieldName);
                default:
                    return ReflectGetValue(target, propertyOrFieldName);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectGetValue(target, propertyOrFieldName);
#endif
        }
        /// <summary>
        /// 动态从 某个类的静态属性 取值，本函数不支持 多级取值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static object GetStaticValue(Type type, string propertyOrFieldName)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentGetValueTypeEnum)
            {
                case GetValueTypeEnum.Emit:
                    return EmitGetStaticValue(type, propertyOrFieldName);
                default:
                    return ReflectGetStaticValue(type, propertyOrFieldName);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectGetStaticValue(type, propertyOrFieldName);
#endif
        }
        /// <summary>
        /// 动态从 某个对象的属性 取值，本函数不支持 多级取值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_GetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static object GetValue(object target, PropertyInfo propertyInfo)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentGetValueTypeEnum)
            {
                case GetValueTypeEnum.Emit:
                    return EmitGetValue(target, propertyInfo);
                default:
                    return ReflectGetValue(target, propertyInfo);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectGetValue(target, propertyInfo);
#endif
        }
        /// <summary>
        /// 动态从 某个类的静态属性 取值，本函数不支持 多级取值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static object GetStaticValue(PropertyInfo propertyInfo)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentGetValueTypeEnum)
            {
                case GetValueTypeEnum.Emit:
                    return EmitGetStaticValue(propertyInfo);
                default:
                    return ReflectGetStaticValue(propertyInfo);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectGetStaticValue(propertyInfo);
#endif
        }
        /// <summary>
        /// 动态从 某个对象的属性 取值，本函数不支持 多级取值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_GetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static object GetValue(object target, FieldInfo fieldInfo)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentGetValueTypeEnum)
            {
                case GetValueTypeEnum.Emit:
                    return EmitGetValue(target, fieldInfo);
                default:
                    return ReflectGetValue(target, fieldInfo);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectGetValue(target, fieldInfo);
#endif
        }
        /// <summary>
        /// 动态从 某个类的静态属性 取值，本函数不支持 多级取值（注意：如果该函数不稳定，请在 配置文件中 将 appSettings.ReflectHelper_SetValueType 试着赋值为 [默认]Reflect, Emit）
        /// </summary>
        public static object GetStaticValue(FieldInfo fieldInfo)
        {
#if (!WindowsCE && !PocketPC)
            switch (CurrentGetValueTypeEnum)
            {
                case GetValueTypeEnum.Emit:
                    return EmitGetStaticValue(fieldInfo);
                default:
                    return ReflectGetStaticValue(fieldInfo);
            }
#endif
#if (WindowsCE || PocketPC)
            return ReflectGetStaticValue(fieldInfo);
#endif
        }

        #endregion



        #region  数 据 转 换

        #region  基 本 数 据 类 型

        public static bool IsMetaType(Type type)
        {
            if (type.IsEnum) return true;       //枚举视为 基本类型
            return hashMetaTypes.ContainsKey(type);
        }
        public static Type GetTypeBySimpleTypeName(string typeName)
        {
            if (string.IsNullOrEmpty(typeName)) return null;

            switch (typeName.ToLower())
            {
                case "string": case "str": return typeofString;
                case "bool": case "boolean": return typeofBoolean;
                case "byte": return typeofByte;
                case "char": return typeofChar;
                case "decimal": return typeofDecimal;
                case "double": return typeofDouble;
                case "short": case "int16": return typeofInt16;
                case "int": case "int32": return typeofInt32;
                case "long": case "int64": return typeofInt64;
                case "sbyte": return typeofSByte;
                case "float": case "single": return typeofSingle;
                case "timespan": return typeofTimeSpan;
                case "datetime": return typeofDateTime;
                case "ushort": case "uint16": return typeofUInt16;
                case "uint": case "uint32": return typeofUInt32;
                case "ulong": case "uint64": return typeofUInt64;
                case "object": case "obj": return typeofObject;
                case "byte[]": case "bytes": return typeofByteArray;
            }

            return Type.GetType(typeName);
        }

        internal static Assembly urtAssembly = Assembly.Load("mscorlib");//Assembly.GetAssembly(Converter.typeofString);
        internal static Type typeofString = typeof(string);
        internal static Type typeofGuid = typeof(Guid);
        internal static Type typeofBoolean = typeof(bool);
        internal static Type typeofByte = typeof(byte);
        internal static Type typeofChar = typeof(char);
        internal static Type typeofDecimal = typeof(decimal);
        internal static Type typeofDouble = typeof(double);
        internal static Type typeofInt16 = typeof(short);
        internal static Type typeofInt32 = typeof(int);
        internal static Type typeofInt64 = typeof(long);
        internal static Type typeofSByte = typeof(sbyte);
        internal static Type typeofSingle = typeof(float);
        internal static Type typeofTimeSpan = typeof(TimeSpan);
        internal static Type typeofDateTime = typeof(DateTime);
        internal static Type typeofUInt16 = typeof(ushort);
        internal static Type typeofUInt32 = typeof(uint);
        internal static Type typeofUInt64 = typeof(ulong);

        internal static Type typeofObject = typeof(object);  //不是基本数据类型
        //internal static Type typeofSystemVoid = typeof(void);
        //internal static Type typeofTypeArray = typeof(Type[]);
        //internal static Type typeofObjectArray = typeof(object[]);
        //internal static Type typeofStringArray = typeof(string[]);
        //internal static Type typeofBooleanArray = typeof(bool[]);
        internal static Type typeofByteArray = typeof(byte[]);
        //internal static Type typeofCharArray = typeof(char[]);
        //internal static Type typeofDecimalArray = typeof(decimal[]);
        //internal static Type typeofDoubleArray = typeof(double[]);
        //internal static Type typeofInt16Array = typeof(short[]);
        //internal static Type typeofInt32Array = typeof(int[]);
        //internal static Type typeofInt64Array = typeof(long[]);
        //internal static Type typeofSByteArray = typeof(sbyte[]);
        //internal static Type typeofSingleArray = typeof(float[]);
        //internal static Type typeofTimeSpanArray = typeof(TimeSpan[]);
        //internal static Type typeofDateTimeArray = typeof(DateTime[]);
        //internal static Type typeofUInt16Array = typeof(ushort[]);
        //internal static Type typeofUInt32Array = typeof(uint[]);
        //internal static Type typeofUInt64Array = typeof(ulong[]);

        internal static Hashtable hashMetaTypes = Hashtable.Synchronized(new Hashtable
                                                   {
                                                       #region  基础数据类型

                                                       { typeofString, 1},
                                                       { typeofGuid, 1},
                                                       { typeofBoolean, 1},
                                                       { typeofByte, 1},
                                                       { typeofChar, 1},
                                                       { typeofDecimal, 1},
                                                       { typeofDouble, 1},
                                                       { typeofInt16, 1},
                                                       { typeofInt32, 1},
                                                       { typeofInt64, 1},
                                                       { typeofSByte, 1},
                                                       { typeofSingle, 1},
                                                       { typeofTimeSpan, 1},
                                                       { typeofDateTime, 1},
                                                       { typeofUInt16, 1},
                                                       { typeofUInt32, 1},
                                                       { typeofUInt64, 1},
                                                       //{ typeofObject, 1},
                                                       //{ typeofSystemVoid, 1},
                                                       //{ typeofTypeArray, 1},
                                                       //{ typeofObjectArray, 1},
                                                       //{ typeofStringArray, 1},
                                                       //{ typeofBooleanArray, 1},
                                                       { typeofByteArray, 1},
                                                       //{ typeofCharArray, 1},
                                                       //{ typeofDecimalArray, 1},
                                                       //{ typeofDoubleArray, 1},
                                                       //{ typeofInt16Array, 1},
                                                       //{ typeofInt32Array, 1},
                                                       //{ typeofInt64Array, 1},
                                                       //{ typeofSByteArray, 1},
                                                       //{ typeofSingleArray, 1},
                                                       //{ typeofTimeSpanArray, 1},
                                                       //{ typeofDateTimeArray, 1},
                                                       //{ typeofUInt16Array, 1},
                                                       //{ typeofUInt32Array, 1},
                                                       //{ typeofUInt64Array, 1},
                                                       #endregion
                                                   });

        #endregion

        public static object ChangeType(object obj, Type type)
        {
            if (type == null || type == typeofObject) return obj;
            if (obj == DBNull.Value || obj == null) return DefaultForType(type);

            Type objType = obj.GetType();
            if (objType == type || type.IsAssignableFrom(objType)) return obj;

            try
            {
                #region  转 换 类 型

                if (type == typeofBoolean) return Tools.ToBoolean(obj);
                if (type == typeofChar) return Tools.ToChar(obj);
                if (type == typeofSByte) return (sbyte)Tools.ToByte(obj);
                if (type == typeofByte) return Tools.ToByte(obj);
                if (type == typeofInt16) return Tools.ToShort(obj);
                if (type == typeofUInt16) return (ushort)Tools.ToDouble(obj);
                if (type == typeofInt32) return Tools.ToInt(obj);
                if (type == typeofUInt32) return (uint)Tools.ToDouble(obj);
                if (type == typeofInt64) return Tools.ToLong(obj);
                if (type == typeofUInt64) return (ulong)Tools.ToDouble(obj);
                if (type == typeofSingle) return Tools.ToFloat(obj);
                if (type == typeofDouble) return Tools.ToDouble(obj);
                if (type == typeofDecimal) return Tools.ToDecimal(obj);
                if (type == typeofDateTime) return Tools.ToDateTime(obj);
                if (type == typeofString) return Tools.ToString(obj);
                if (type == typeofGuid) return Tools.ToGuid(obj);
                if (type == typeofObject) return obj;

                #endregion

#if (!WindowsCE && !PocketPC)
                return Convert.ChangeType(obj, type);
#endif
#if (WindowsCE || PocketPC)
                return Convert.ChangeType(obj, type, null);
#endif
            }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (Exception exp)
            {
                throw new InvalidCastException(string.Format("ChangeType(object, Type) Error: Value: '{0}' Can Not Cast To Type: '{1}' (InnerException: {2})", obj, type, exp.Message));
            }
        }
        public static object DefaultForType(Type type)
        {
            if (type == null) return null;
            return type.IsValueType ? Activator.CreateInstance(type) : null;
        }

        #endregion

        #region  获 取 成 员

        public static Type GetPropertyOrFieldType(Type type, string propertyOrFieldName)
        {
            PropertyInfo propertyInfo = GetPropertyInfo(type, propertyOrFieldName);
            if (propertyInfo != null) return propertyInfo.PropertyType;

            FieldInfo fieldInfo = GetFieldInfo(type, propertyOrFieldName);
            if (fieldInfo != null) return fieldInfo.FieldType;

            return null;
        }

        public static PropertyInfo GetPropertyInfo(Type type, string propertyName)
        {
            if (type == null || string.IsNullOrEmpty(propertyName)) return null;

            PropertyInfo propertyInfo = type.GetProperty(propertyName, Property_Field_BindingFlags);
            return propertyInfo;
        }
        public static List<PropertyInfo> GetPropertyInfos(Type type)
        {
            if (type == null) return null;
            PropertyInfo[] propertyInfos = type.GetProperties(Property_Field_BindingFlags);
            List<PropertyInfo> listProperty = new List<PropertyInfo>();
            listProperty.AddRange(propertyInfos);
            return listProperty;
        }

        public static FieldInfo GetFieldInfo(Type type, string fieldName)
        {
            if (type == null || string.IsNullOrEmpty(fieldName)) return null;

            FieldInfo fieldInfo = type.GetField(fieldName, Property_Field_BindingFlags);
            return fieldInfo;
        }
        public static List<FieldInfo> GetFieldInfos(Type type)
        {
            if (type == null) return null;
            FieldInfo[] fieldInfos = type.GetFields(Property_Field_BindingFlags);
            List<FieldInfo> listField = new List<FieldInfo>();
            listField.AddRange(fieldInfos);
            return listField;
        }

        #endregion




        [Serializable]
        internal enum SetValueTypeEnum { None, Reflect, Emit }
        [Serializable]
        internal enum GetValueTypeEnum { None, Reflect, Emit }
        public delegate void SetValueDelegate(object target, object value);
        public delegate void StaticSetValueDelegate(object value);
        public delegate object GetValueDelegate(object target);
        public delegate object StaticGetValueDelegate();

        #endregion
    }


    /// <summary>
    /// 表示一个 程序集丢失异常.
    /// </summary>
    [Serializable]
    internal class AssemblyMissException : Exception
    {
        public static AssemblyMissException Create(Assembly assembly, AssemblyName[] refMissAssemblies, Exception innerException)
        {
            string assemblyFullName = assembly == null ? "NULL" : assembly.FullName;
            string innerExpMsg = innerException == null ? "NULL" : innerException.Message;
            List<string> listMissFullName = new List<string>();
            foreach (AssemblyName item in refMissAssemblies)
                listMissFullName.Add(item.FullName);

            string expMsg = string.Format("RefAssembly Is Miss.\r\nAssembly:\r\n    {0}\r\nMissAssemblies:\r\n    {1}\r\nInnerException:\r\n{2}", assemblyFullName, string.Join("\r\n    ", listMissFullName.ToArray()), innerExpMsg);

            AssemblyMissException exp = new AssemblyMissException(expMsg, innerException);
            exp.Assembly = assembly;
            exp.RefMissAssemblies = refMissAssemblies;
            return exp;
        }

        public AssemblyMissException() : base()
        {
        }
        public AssemblyMissException(string message, Exception innerException) : base(message, innerException)
        {
        }


        public Assembly Assembly { get; private set; }
        public AssemblyName[] RefMissAssemblies { get; private set; }
    }



#if (!WindowsCE && !PocketPC)

    /// <summary>
    /// 表示一个 函数的 定义信息 类型信息
    /// </summary>
    internal class ReflectMethodInfo
    {
        private List<Type> m_ParamTypes;



        public MethodInfo Method { get; private set; }
        public ReflectGenericDefine GenericDefine { get; private set; }
        public List<Type> ParamTypes
        {
            get
            {
                if (m_ParamTypes == null) m_ParamTypes = new List<Type>();
                return m_ParamTypes;
            }
            private set
            {
                if (m_ParamTypes != value)
                {
                    if (m_ParamTypes == null) m_ParamTypes = new List<Type>();
                    else m_ParamTypes.Clear();
                    m_ParamTypes.AddRange(value);
                }
            }
        }
        public Type ReturnType { get; private set; }


        public bool IsStatic { get; private set; }
        public bool IsAction { get; private set; }
        public bool IsFunc { get; private set; }
        public Type DeclaringType { get; private set; }

        public int ParamTypesCount
        {
            get { return m_ParamTypes == null ? 0 : m_ParamTypes.Count; }
        }
        public List<Type> ParamAndReturnTypes
        {
            get
            {
                List<Type> listTemp = new List<Type>(ParamTypes);
                listTemp.Add(ReturnType);
                return listTemp;
            }
        }

        public Type GetGenericRealType(Type paramType)
        {
            return ReflectMethodInfo.GetGenericRealType(paramType, GenericDefine);
        }










        public static Type GetGenericRealType(Type paramType, ReflectGenericDefine genericDefine)
        {
            if (paramType.ContainsGenericParameters) //如果当前类型 包括泛型参数, 则尝试探测出 实际的类型
            {
                try
                {
                    if (paramType.IsGenericParameter/* || paramType.IsGenericType*/)
                    {
                        if (genericDefine == null || genericDefine.NonGeneric) throw GenericUnknowException.Create(paramType, string.Format("Generic Type '{0}' Is Unknow.", paramType.Name));

                        Type realParamType = genericDefine[paramType.Name];
                        if (realParamType == null || realParamType.ContainsGenericParameters) throw GenericUnknowException.Create(paramType, string.Format("Generic Type '{0}' Is Unknow.", paramType.Name));

                        return realParamType;
                    }
                    else
                    {
                        Type genericType = paramType;
                        if (!genericType.IsGenericTypeDefinition)
                            genericType = genericType.GetGenericTypeDefinition();


                        Type[] genericArgs = paramType.GetGenericArguments();

                        List<Type> listGenericArg = new List<Type>();
                        foreach (Type genericArg in genericArgs)
                        {
                            if (!genericArg.ContainsGenericParameters) listGenericArg.Add(genericArg);
                            else
                            {
                                Type realGenericArg = GetGenericRealType(genericArg, genericDefine);
                                listGenericArg.Add(realGenericArg);
                            }
                        }

                        return genericType.MakeGenericType(listGenericArg.ToArray());
                    }
                }
                catch (System.Threading.ThreadAbortException) { throw; }
                catch (GenericUnknowException exp)
                {
                    throw GenericUnknowException.Create(paramType, exp.Info, exp);
                }
            }
            else
                return paramType;
        }
        public static MethodInfo GetGenericRealMethodInfo(MethodInfo method, ReflectGenericDefine genericDefine)
        {
            if (method == null) return null;

            //如果 类型的泛型 没有定义, 则尝试探测出 精确的类型定义 和 精确类型定义 下的 当前函数
            Type declareingType = method.DeclaringType;
            if (declareingType != null && declareingType.IsGenericType && declareingType.ContainsGenericParameters)
            {
                Type declareingType2 = ReflectMethodInfo.GetGenericRealType(declareingType, genericDefine);
                ParameterInfo[] methodParam = method.GetParameters();
                List<Type> listParamType = new List<Type>();
                foreach (ParameterInfo param in methodParam)
                {
                    Type realParamType = genericDefine.IsMethodGeneric(param.ParameterType.Name)
                        ? param.ParameterType
                        : ReflectMethodInfo.GetGenericRealType(param.ParameterType, genericDefine);
                    listParamType.Add(realParamType);
                }
                MethodInfo method2 = declareingType2.GetMethod(method.Name, listParamType.ToArray());
                if (method2 == null) method2 = declareingType2.GetMethod(method.Name);
                if (method2 == null) throw GenericUnknowException.Create(method, string.Format("Can't Find Method '{1}' From Class '{0}'.", GenericUnknowException.GetKonwTypeName(declareingType2), method.Name));
                method = method2;

                //ParameterInfo[] method2Param = method2.GetParameters();
                //List<Type> listParamType2 = new List<Type>();
                //foreach (ParameterInfo param in method2Param)
                //{
                //    Type realParamType = ReflectMethodInfo.GetGenericRealType(param.ParameterType, genericDefine);
                //    listParamType2.Add(realParamType);
                //}
                //Console.WriteLine(method2);
            }


            if (method.ContainsGenericParameters) //如果当前函数 包括泛型参数, 则尝试探测出 实际的函数定义
            {
                //if (method.IsGenericMethod) { }
                //else { }
                MethodInfo genericMethod = method;

                try
                {
                    if (!genericMethod.IsGenericMethodDefinition)
                        genericMethod = genericMethod.GetGenericMethodDefinition();

                    Type[] genericArgs = method.GetGenericArguments();

                    List<Type> listGenericArg = new List<Type>();
                    foreach (Type genericArg in genericArgs)
                    {
                        if (!genericArg.ContainsGenericParameters) listGenericArg.Add(genericArg);
                        else
                        {
                            Type realGenericArg = GetGenericRealType(genericArg, genericDefine);
                            listGenericArg.Add(realGenericArg);
                        }
                    }

                    return genericMethod.MakeGenericMethod(listGenericArg.ToArray());
                }
                catch (System.Threading.ThreadAbortException) { throw; }
                catch (GenericUnknowException exp)
                {
                    throw GenericUnknowException.Create(genericMethod, exp.Info, exp);
                }
            }
            else
                return method;
        }
        public static MethodInfo GetGenericRealMethodInfo(MethodInfo method, Type[] classGenericTypes, Type[] methodGenericTypes)
        {
            if (method == null) return null;

            ReflectGenericDefine genericDefine = GetMethodGenericDefine(method);
            if (genericDefine.NonGeneric) return method;

            genericDefine.PerfectGenericType(classGenericTypes, methodGenericTypes);
            return GetGenericRealMethodInfo(method, genericDefine);
        }
        public static ReflectGenericDefine GetMethodGenericDefine(MethodInfo method)
        {
            if (method == null) return null;
            ReflectGenericDefine define = new ReflectGenericDefine();
            if(! method.ContainsGenericParameters) return define;

            Type dclaringType = method.DeclaringType;

            Type[] classGenericDArgs = (dclaringType == null || !(dclaringType.IsGenericType || dclaringType.IsGenericParameter)) ? null : dclaringType.GetGenericTypeDefinition().GetGenericArguments();
            Type[] methodGenericDArgs = (method == null || !(method.IsGenericMethod)) ? null : method.GetGenericMethodDefinition().GetGenericArguments();

            Type[] classGenericArgs = dclaringType == null ? null : dclaringType.GetGenericArguments();
            Type[] methodGenericArgs = method.GetGenericArguments();

            if (classGenericArgs != null)
                for (int i = 0, count = classGenericArgs.Length; i < count; i++)
                {
                    Type classGenericArg = classGenericArgs[i];
                    Type classGenericDArg = (classGenericDArgs == null || classGenericDArgs.Length <= i) ? null : classGenericDArgs[i];
                    ReflectGenericInfo item = new ReflectGenericInfo();
                    item.IsClassGeneric = true;
                    item.Name = classGenericDArg != null ? classGenericDArg.Name : classGenericArg.Name;
                    item.IsConstGeneric = !classGenericArg.ContainsGenericParameters;
                    item.GenericType = item.IsConstGeneric ? classGenericArg : null;
                    define.GenericInfos[item.Name] = item;
                }

            if (methodGenericArgs != null)
                for (int i = 0, count = methodGenericArgs.Length; i < count; i++)
                {
                    Type methodGenericArg = methodGenericArgs[i];
                    Type methodGenericDArg = (methodGenericDArgs == null || methodGenericDArgs.Length <= i) ? null : methodGenericDArgs[i];
                    ReflectGenericInfo item = new ReflectGenericInfo();
                    item.IsMethodGeneric = true;
                    item.Name = methodGenericDArg != null ? methodGenericDArg.Name : methodGenericArg.Name;
                    item.GenericType = methodGenericArg;
                    item.IsConstGeneric = !methodGenericArg.ContainsGenericParameters;
                    item.GenericType = item.IsConstGeneric ? methodGenericArg : null;
                    define.GenericInfos[item.Name] = item;
                }

            return define;
        }

        public static ReflectMethodInfo Create(MethodInfo method, Type[] classGenericTypes, Type[] methodGenericTypes)
        {
            try
            {
                ReflectGenericDefine genericDefine = GetMethodGenericDefine(method);
                genericDefine.PerfectGenericType(classGenericTypes, methodGenericTypes);

                ReflectMethodInfo methodInfo = new ReflectMethodInfo();
                methodInfo.GenericDefine = genericDefine;


                MethodInfo method2 = GetGenericRealMethodInfo(method, genericDefine);
                methodInfo.Method = method2;

                ParameterInfo[] methodParams = method2.GetParameters();
                methodInfo.IsAction = method2.ReturnType == typeof(void);
                methodInfo.IsFunc = method2.ReturnType != typeof(void);
                methodInfo.IsStatic = method2.IsStatic;



                Type dclaringType = methodInfo.Method.DeclaringType;
                methodInfo.DeclaringType = ReflectMethodInfo.GetGenericRealType(dclaringType, genericDefine);


                List<Type> listParamType = new List<Type>();

                if (!methodInfo.IsStatic) listParamType.Add(dclaringType);

                foreach (ParameterInfo param in methodParams)
                {
                    Type realParamType = ReflectMethodInfo.GetGenericRealType(param.ParameterType, genericDefine);
                    listParamType.Add(realParamType);
                }

                Type realReturnType = method2.ReturnParameter == null ? null : ReflectMethodInfo.GetGenericRealType(method2.ReturnParameter.ParameterType, genericDefine);

                methodInfo.ParamTypes = listParamType;
                methodInfo.ReturnType = realReturnType;
                return methodInfo;
            }
            catch (System.Threading.ThreadAbortException) { throw; }
            catch (GenericUnknowException exp)
            {
                throw GenericUnknowException.Create(method, exp.Info, exp);
            }
        }
    }

    /// <summary>
    /// 一个函数的 所有泛型定义
    /// </summary>
    internal class ReflectGenericDefine
    {
        private SimpDict<string, ReflectGenericInfo> m_GenericInfos;



        public Type this[string name]
        {
            get
            {
                ReflectGenericInfo genericInfo = GenericInfos[name];
                return genericInfo == null ? null : genericInfo.GenericType;
            }
        }
        /// <summary>
        /// 当前反省定义 不包含任何 泛型参数
        /// </summary>
        public bool NonGeneric
        {
            get { return m_GenericInfos == null || m_GenericInfos.Count <= 0; }
        }
        /// <summary>
        /// 泛型参数的个数
        /// </summary>
        public int GenericCount
        {
            get { return m_GenericInfos == null ? 0 : m_GenericInfos.Count; }
        }
        /// <summary>
        /// 无法探测实际类型的泛型数目
        /// </summary>
        public int UnknowGenericCount
        {
            get
            {
                int count = 0;
                if (m_GenericInfos != null && m_GenericInfos.Count >= 1)
                {
                    foreach (ReflectGenericInfo item in m_GenericInfos.Values)
                    {
                        if (item == null || item.GenericType == null || item.GenericType.ContainsGenericParameters) count++;
                    }
                }
                return count;
            }
        }
        public SimpDict<string, ReflectGenericInfo> GenericInfos
        {
            get
            {
                if (m_GenericInfos == null) m_GenericInfos = new SimpDict<string, ReflectGenericInfo>();
                return m_GenericInfos;
            }
            private set
            {
                if (m_GenericInfos != value)
                {
                    if (m_GenericInfos == null) m_GenericInfos = new SimpDict<string, ReflectGenericInfo>();
                    else m_GenericInfos.Clear();
                    m_GenericInfos.AddRange(value);
                }
            }
        }

        /// <summary>
        /// 判断指定 泛型类型名称 是否是 定义在类上的 泛型
        /// </summary>
        public bool IsClassGeneric(string name)
        {
            ReflectGenericInfo genericInfo = GenericInfos[name];
            return genericInfo != null && genericInfo.IsClassGeneric;
        }
        /// <summary>
        /// 判断指定 泛型类型名称 是否是 定义在函数上的 泛型
        /// </summary>
        public bool IsMethodGeneric(string name)
        {
            ReflectGenericInfo genericInfo = GenericInfos[name];
            return genericInfo != null && genericInfo.IsMethodGeneric;
        }







        public void PerfectGenericType(Type[] classGenericTypes, Type[] methodGenericTypes)
        {
            SimpDict<string, ReflectGenericInfo> hash = GenericInfos;
            List<ReflectGenericInfo> listCG = new List<ReflectGenericInfo>(hash.Values);
            List<ReflectGenericInfo> listMG = new List<ReflectGenericInfo>(hash.Values);
            listCG.RemoveAll(x => !x.IsClassGeneric);
            listMG.RemoveAll(x => !x.IsMethodGeneric);

            List<ReflectGenericInfo> listCG2 = listCG.FindAll(x => x.IsUnknow);
            List<ReflectGenericInfo> listMG2 = listMG.FindAll(x => x.IsUnknow);

            int cgCount = classGenericTypes == null ? 0 : classGenericTypes.Length;
            int mgCount = methodGenericTypes == null ? 0 : methodGenericTypes.Length;

            List<ReflectGenericInfo> listCGT = listCG2.Count == cgCount ? listCG2 : listCG;
            List<ReflectGenericInfo> listMGT = listMG2.Count == mgCount ? listMG2 : listMG;

            for(int i=0, count = listCGT.Count ; i<count ;i++)
            {
                ReflectGenericInfo item = listCGT[i];
                Type type = (classGenericTypes == null || classGenericTypes.Length < i) ? null : classGenericTypes[i];
                if (type != null) item.GenericType = type;
            }

            for (int i = 0, count = listMGT.Count; i < count; i++)
            {
                ReflectGenericInfo item = listMGT[i];
                Type type = (methodGenericTypes == null || methodGenericTypes.Length < i) ? null : methodGenericTypes[i];
                if (type != null) item.GenericType = type;
            }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            if (m_GenericInfos != null && m_GenericInfos.Count>=1)
            {
                foreach (string key in m_GenericInfos.Keys)
                    sb.AppendLine(((object) m_GenericInfos[key] ?? string.Empty).ToString());
            }

            return sb.ToString();
        }


    }

    /// <summary>
    /// 泛型定义的 反射信息
    /// </summary>
    internal class ReflectGenericInfo
    {
        private string m_Name = string.Empty;

        /// <summary>
        /// 泛型在 类定义 和 函数定义 中的 名称
        /// </summary>
        public string Name
        {
            get { return m_Name; }
            set { m_Name = (value ?? string.Empty).Trim(); }
        }
        /// <summary>
        /// 探测的 实际泛型类型
        /// </summary>
        public Type GenericType { get; internal set; }

        /// <summary>
        /// 当前泛型类型 暂不确定
        /// </summary>
        public bool IsUnknow
        {
            get { return GenericType == null || GenericType.ContainsGenericParameters; }
        }
        /// <summary>
        /// 当前探测的 GenericType 实际泛型类型, 是通过程序代码探测出来的, 而不是后期完善的结果 
        /// </summary>
        public bool IsConstGeneric { get; internal set; }

        /// <summary>
        /// 当前泛型定义在 类定义上
        /// </summary>
        public bool IsClassGeneric { get; internal set; }
        /// <summary>
        /// 当前泛型定义在 函数定义上
        /// </summary>
        public bool IsMethodGeneric { get; internal set; }



        public override string ToString()
        {
            return string.Format("{0} \t:{1}", Name, GenericType);
        }
    }

    /// <summary>
    /// 表示一个 泛型类型 无法被探测 的异常.
    /// </summary>
    [Serializable]
    internal class GenericUnknowException : Exception
    {
        public static GenericUnknowException Create(MemberInfo member, string info)
        {
            return Create(member, info, null);
        }
        public static GenericUnknowException Create(MemberInfo member, string info, Exception innerException)
        {
            string memberStr = member is Type
                                   ? GetKonwTypeName((Type) member)
                                   : member is MethodInfo
                                         ? GetKonwMethodDefine((MethodInfo) member)
                                         : member.ToString();

            string expMsg = string.Format("GenericType Is Unknow.\r\nMember:\r\n    {0}\r\nInfo:\r\n    {1}", memberStr, info);

            GenericUnknowException exp = new GenericUnknowException(expMsg, null);
            exp.Member = member;
            exp.Info = info;
            return exp;
        }


        public GenericUnknowException() : base()
        {
        }
        public GenericUnknowException(string message, Exception innerException) : base(message, innerException)
        {
        }

        public MemberInfo Member { get; private set; }
        public string Info { get; private set; }


        private static readonly Regex m_RegGenericNum = new Regex(@"(?<=[\w\$])`[\d]+(?=\<)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        public static string GetKonwTypeName(Type type)
        {
            if (type == null) return string.Empty;

            Type[] genTypes = type.GetGenericArguments();
            string[] listTypeName = new string[genTypes.Length];
            for (int i = 0, count = genTypes.Length; i < count; i++)
                listTypeName[i] = GetKonwTypeName(genTypes[i]);

            string result = genTypes.Length > 0 ? string.Format("{0}<{1}>", type.Name, string.Join(",", listTypeName)) : type.Name;
            result = m_RegGenericNum.Replace(result, string.Empty);
            return result;
        }
        public static string GetKonwMethodDefine(MethodInfo method)
        {
            if (method == null) return string.Empty;

            Type[] genTypes = method.GetGenericArguments();
            string[] listTypeName = new string[genTypes.Length];
            for (int i = 0, count = genTypes.Length; i < count; i++)
                listTypeName[i] = GetKonwTypeName(genTypes[i]);

            ParameterInfo[] mtdParams = method.GetParameters();
            string[] listParamName = new string[mtdParams.Length];
            for (int i = 0, count = mtdParams.Length; i < count; i++)
            {
                string type = GetKonwTypeName(mtdParams[i].ParameterType);
                listParamName[i] = string.Format("{0} {1}", type, mtdParams[i].Name);
            }

            string retTypeName = GetKonwTypeName(method.ReturnType);
            string decTypeName = GetKonwTypeName(method.DeclaringType);
            string @pub = method.IsPrivate ? "private" : (method.IsPublic ? "public" : string.Empty);
            string @sta = method.IsStatic ? " static" : string.Empty; 

            string result = genTypes.Length > 0
                       ? string.Format("{6}{5} {4} {3}.{0}<{1}>({2})", method.Name, string.Join(", ", listTypeName), string.Join(", ", listParamName), decTypeName, retTypeName, @sta, @pub)
                       : string.Format("{5}{4} {3} {2}.{0}({1})", method.Name, string.Join(", ", listParamName), decTypeName, retTypeName, @sta, @pub);


            result = m_RegGenericNum.Replace(result, string.Empty);
            return result;
        }

    }

#endif



    internal delegate void EmitAction();
    internal delegate void EmitAction<in T1>(T1 arg1);
    internal delegate void EmitAction<in T1, in T2>(T1 arg1, T2 arg2);
    internal delegate void EmitAction<in T1, in T2, in T3>(T1 arg1, T2 arg2, T3 arg3);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
    internal delegate void EmitAction<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, in T17>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16, T17 arg17);

    internal delegate TResult EmitFunc<out TResult>();
    internal delegate TResult EmitFunc<in T, out TResult>(T arg);
    internal delegate TResult EmitFunc<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
    internal delegate TResult EmitFunc<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, in T17, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16, T17 arg17);




}
